zoukankan      html  css  js  c++  java
  • 线程的执行状态讲解

    在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();
      }
    }

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

  • 相关阅读:
    Centos下Oracle11gR2安装教程与自动化配置脚本
    你知道CPU结构也会影响Redis性能吗?
    谈谈InnoDB中的B+树索引
    理论:第十一章:大厂程序员如何使用GitHub快速开发学习
    理论:第十四章:生产环境服务器变慢如何诊断,性能评估
    理论:第十三章:堆溢出,栈溢出的出现场景以及解决方案
    理论:第十二章:Dubbo的运行原理,支持什么协议,与SpringCould相比它为什么效率要高一些,Zookeeper底层原理
    理论:第十章:公平锁,非公平锁,可重入锁,递归锁,自旋锁,读写锁,悲观锁,乐观锁,行锁,表锁,死锁,分布式锁,线程同步锁分别是什么?
    理论:第九章:JVM内存模型,算法,垃圾回收器,调优,四大引用,常见的JVM错误,类加载机制(双亲委派),创建一个对象,这个对象在内存中是怎么分配的?
    理论:第八章:线程是什么,有几种实现方式,它们之间的区别是什么,线程池实现原理,JUC并发包,ThreadLocal与Lock和Synchronize区别
  • 原文地址:https://www.cnblogs.com/cxyxiaobao/p/12385900.html
Copyright © 2011-2022 走看看