线程的执行状态讲解

在java的类中有线程状态的描述:java.lang.thread.state

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

1 new :  表示线程的创建状态,并且尚未启动

2  runnable: 可运行的线程状态,等待cpu的调度

3  blocked: 线程阻塞等待监视器锁定的状态

4   wating:  线程等待的状态,

5 timed waiting   具有等待时间的等待状态

6 terminate  线程执行完毕的状态:

public class Demo2 {
    public static Thread thread1;
    public static Demo2 obj;

    public static void main(String[] args) throws Exception {
        // 第一种状态切换 - 新建 -> 运行 -> 终止
        System.out.println("#######第一种状态切换  - 新建 -> 运行 -> 终止################################");
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1当前状态:" + Thread.currentThread().getState().toString());
                System.out.println("thread1 执行了");
            }
        });
        System.out.println("没调用start方法,thread1当前状态:" + thread1.getState().toString());
        thread1.start();
        Thread.sleep(2000L); // 等待thread1执行结束,再看状态
        System.out.println("等待两秒,再看thread1当前状态:" + thread1.getState().toString());
        // thread1.start(); TODO 注意,线程终止之后,再进行调用,会抛出IllegalThreadStateException异常

        System.out.println();
        System.out.println("############第二种:新建 -> 运行 -> 等待 -> 运行 -> 终止(sleep方式)###########################");
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {// 将线程2移动到等待状态,1500后自动唤醒
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2当前状态:" + Thread.currentThread().getState().toString());
                System.out.println("thread2 执行了");
            }
        });
        System.out.println("没调用start方法,thread2当前状态:" + thread2.getState().toString());
        thread2.start();
        System.out.println("调用start方法,thread2当前状态:" + thread2.getState().toString());
        Thread.sleep(200L); // 等待200毫秒,再看状态
        System.out.println("等待200毫秒,再看thread2当前状态:" + thread2.getState().toString());
        Thread.sleep(3000L); // 再等待3秒,让thread2执行完毕,再看状态
        System.out.println("等待3秒,再看thread2当前状态:" + thread2.getState().toString());

        System.out.println();
        System.out.println("############第三种:新建 -> 运行 -> 阻塞 -> 运行 -> 终止###########################");
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (Demo2.class) {
                    System.out.println("thread3当前状态:" + Thread.currentThread().getState().toString());
                    System.out.println("thread3 执行了");
                }
            }
        });
        synchronized (Demo2.class) {
            System.out.println("没调用start方法,thread3当前状态:" + thread3.getState().toString());
            thread3.start();
            System.out.println("调用start方法,thread3当前状态:" + thread3.getState().toString());
            Thread.sleep(200L); // 等待200毫秒,再看状态
            System.out.println("等待200毫秒,再看thread3当前状态:" + thread3.getState().toString());
        }
        Thread.sleep(3000L); // 再等待3秒,让thread3执行完毕,再看状态
        System.out.println("等待3秒,让thread3抢到锁,再看thread3当前状态:" + thread3.getState().toString());

    }
}

那线程如何终止呢:

采用interrupt方法,是有stop方法,但是会造成线程安全的问题:

public class Demo3 {
  public static void main(String[] args) throws InterruptedException {
    StopThread thread = new StopThread();
    thread.start();
    // 休眠1秒,确保i变量自增成功
    Thread.sleep(1000);
    // 暂停线程
   //  thread.stop(); // 错误的终止
   thread.interrupt(); // 正确终止
    while (thread.isAlive()) {
      // 确保线程已经终止
    } // 输出结果
    thread.print();
  }
}

同事这种方法也可以进行线程异常的一个捕获,开发者可以执行自己的逻辑

猜你喜欢

转载自www.cnblogs.com/cxyxiaobao/p/12385900.html
今日推荐