zoukankan      html  css  js  c++  java
  • 线程的六种状态

    1、查看源码

    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;
        }

    一共有六种状态。

    2、六种状态

    (1)新建(NEW)

    new关键字创建一个线程之后,该线程处于新建状态。jvm为线程分配内存,初始化成员变量值

    (2)运行(RUNABLE)

    就绪(ready):

    当线程对象调用了start()方法后,该线程处于就绪状态。jvm为线程创建方法栈和程序计数器,等待线程调度器调度

    运行(running):

    就绪状态的线程获得CPU资源,开始运行run方法,该线程处于运行状态

    (3)阻塞

    线程调用sleep方法主动放弃所占用的处理器资源

    线程调用了一个阻塞式IO方法,在该方法返回之前,该线程被阻塞

    线程试图获得一个同步锁(同步监视器),但是该锁正在被其它线程持有

    线程正在等待某个通知

    public class Test {
        static class Toilet{
            public synchronized void use(){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void main(String[] args) throws InterruptedException {
           Toilet toilet=new Toilet();
           Thread a=new Thread(){
             public  void  run(){
                 toilet.use();
             }
           };
           a.start();
           Thread.sleep(1000);
            Thread b=new Thread(){
                public  void  run(){
                    toilet.use();
                }
            };
            b.start();
            Thread.sleep(1000);
            System.out.println(b.getState());
        }
    }

    (4)等待(WAITING)

      处于这种状态的线程不会被分配CPU执行时间,它们要等待被显式地唤醒,否则会处于无限期等待的状态。例如:线程拿到锁之后发现当前线程的执行条件不满足,需要暂时停止执行,以便让CPU资源供其他线程执行

    public class Test {
        static class TEst{
            public synchronized void use(){
                try {
                    System.out.println("a");
                    System.out.println("b");
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void main(String[] args) throws InterruptedException {
             TEst tEst=new TEst();
                Thread thread=new Thread(){
                    public void run(){
                        tEst.use();
                    }
             };
                thread.start();
                Thread.sleep(1000);
                System.out.println(thread.getState());
        }
    }

    如:上面的程序缺乏b的时候就会进入等待状态

    (5)超时等待

    处于这种状态的线程不会被分配CPU执行时间,不过无须无限期等待被其他线程显示地唤醒,在达到一定时间后它们会自动唤醒

    public class Test {
        static class TEst{
            public synchronized void use(){
                try {
                    System.out.println("a");
                    System.out.println("b");
                    wait(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void main(String[] args) throws InterruptedException {
             TEst tEst=new TEst();
                Thread thread=new Thread(){
                    public void run(){
                        tEst.use();
                    }
             };
                thread.start();
                Thread.sleep(1000);
                System.out.println(thread.getState());
        }
    }
    a
    b
    TIMED_WAITING

    (6)死亡

    线程会以如下的三种方式结束,结束后就进入死亡状态:·

    run()或call()方法执行完成,线程正常结束

    线程抛出一个未捕获的Exception或Error

    调用该线程的stop方法来结束该线程,该方法容易导致死锁,不推荐使用

    3、线程的生命周期

    4、线程的状态举例

    public class StateTest implements Runnable {
        @Override
        public void run() {
    
        }
    
        public static void main(String[] args) {
            Thread thread = new Thread(() -> {
                for (int i = 1; i < 5; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("---------------");
            });
    
            Thread.State state = thread.getState();
            System.out.println(state);
    
            thread.start();
            state = thread.getState();
            System.out.println(state);
    
            while (state!=Thread.State.TERMINATED){//只要线程不终止,就一直输出线程的状态
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                state=thread.getState();
                System.out.println(state);
            }
        }
    }

    测试:

    NEW
    RUNNABLE
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    TIMED_WAITING
    ---------------
    TERMINATED
    每个人都会有一段异常艰难的时光 。 生活的压力 , 工作的失意 , 学业的压力。 爱的惶惶不可终日。 挺过来的 ,人生就会豁然开朗。 挺不过来的 ,时间也会教你 ,怎么与它们握手言和 ,所以不必害怕的。 ——杨绛
  • 相关阅读:
    【压测】压力测试工具siege的用法
    五大python自动化框架学习
    自动化“监视”剩余内存&句柄数
    iperf 使用小窍门
    测试 USB 的 读写
    pppoe环境下的mtu和mss的配合问题
    您保存的文件格式可能含有不兼容的功能 是否已保持工作簿这种格式
    pycharm2018永久破解的方法
    Linux如何快速跳转到文档开头或者末尾
    打造自己的Ubuntu渗透利器--Nmap、Zenmap、Sqlmap安装
  • 原文地址:https://www.cnblogs.com/zhai1997/p/13625255.html
Copyright © 2011-2022 走看看