Home > Java > javaTutorial > body text

Java thread status and its meaning

WBOY
Release: 2023-04-21 18:01:16
forward
1169 people have browsed it

Why you need to understand the status of java threads

High multi-thread concurrency is an ability that junior developers must master to move towards intermediate and advanced developers. A sky-high building rises from the ground. After understanding this part in depth Before, we need to clarify the most basic concept, that is, what are the states of threads.

Looking at the states of Java threads from the source code

Thanks to the open source spirit, we can intuitively analyze and see In Java, what are the states of threads? The enumeration class that records all states of threads in Java is

<code>java.lang.Thread.State</code> 
Copy after login

From the source code, we can see that there are a total of 6 states of threads in Java: NEW, RUNNABLE, BLOCKED , WAITING, TIMED_WAITING, TERMINATED. Let's take a look at the detailed source code and the meaning of various thread states.

<code>public enum State {<br>    /**<br>     * 线程对象实例化但是还没有调用start方法.<br>     */<br>    NEW,<br><br>    /**<br>     * 线程处于可运行状态, 这个状态在虚拟机中<br>     * 看来是正在执行的, 但是实际可能在等待<br>     * 操作系统的资源, 比如等待CPU资源.<br>     * 注意Java线程状态只有RUNNABLE而没有RUNNING<br>     */<br>    RUNNABLE,<br><br>    /**<br>     * 阻塞状态的线程可能在等待获取锁,<br>     * 也可能是调用了wait方法后被notify方法<br>     * 唤醒, 再次尝试获取锁, 进入阻塞状态<br>     * {@link Object#wait() Object.wait}.<br>     */<br>    BLOCKED,<br><br>    /**<br>     * 等待状态, 此状态由于调用wait, join, park方法导致<br>     * <ul><br>     *   <li>{@link Object#wait() Object.wait} with no timeout</li><br>     *   <li>{@link #join() Thread.join} with no timeout</li><br>     *   <li>{@link LockSupport#park() LockSupport.park}</li><br>     * </ul><br>     *<br>     * 线程进入等待状态后, 等待notify, notifyAll,<br>     * 特定线程执行完毕, unpark方法<br>     * 然后转换为RUNNABLE状态<br>     */<br>    WAITING,<br><br>    /**<br>     * 有最大时间限制的等待状态<br>     * 可能由调用如下方法导致<br>     * <ul><br>     *   <li>{@link #sleep Thread.sleep}</li><br>     *   <li>{@link Object#wait(long) Object.wait} with timeout</li><br>     *   <li>{@link #join(long) Thread.join} with timeout</li><br>     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li><br>     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li><br>     * </ul><br>     */<br>    TIMED_WAITING,<br><br>    /**<br>     * 终止状态, 线程执行完毕后会进入<br>     * TERMINATED状态<br>     * 并且不能再转换成其它状态<br>     */<br>    TERMINATED;<br>}</code>  
  
Copy after login

10 lines of code exhaust the 6 states of threads

In order to enhance memory , below we use 10 effective codes to intuitively display the 6 states of Java threads.

<code>/**<br> * 如下展示了java线程的6种状态<br> * NEW 线程对象新创建还未start<br> * RUNNABLE 线程已经启动, 线程在JVM中正在运行, 不过在系统层面可能在等待系统资源<br> * BLOCKED 线程等待获取锁<br> * WAITING 线程被LockSupport#park(),<br> * Object#wait()或者Thread.join, 等待被unpark或者notify或者其他新城join完毕<br> * TIMED_WAITING 线程sleep或者wait(long),<br> * LockSupport#parkNanos LockSupport.parkNanos, 等待指定时间后继续执行<br> * TERMINATED 线程执行完毕, 已经被终止<br> * @throws BrokenBarrierException<br> * @throws InterruptedException<br> */<br>@Test<br>public void testThreadStatus() throws BrokenBarrierException, InterruptedException {<br>    CyclicBarrier cyclicBarrier = new CyclicBarrier(2);<br>    Thread thread = new Thread(() -> {<br>        try {<br>            LockSupport.park(this);<br>            TimeUnit.SECONDS.sleep(5);<br>            synchronized (ThreadTest.class) {<br>                // 尝试获取锁, 获取不到进入Blocked状态等待锁<br>            }<br>            cyclicBarrier.await();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        } catch (BrokenBarrierException e) {<br>            e.printStackTrace();<br>        }<br>    });<br>    log.info("线程创建还未启动, 状态为: {}", thread.getState());<br>    thread.start();<br>    log.info("线程已经启动, 状态为: {}", thread.getState());<br>    TimeUnit.SECONDS.sleep(1);<br>    log.info("线程已经park, 状态为: {}", thread.getState());<br>    LockSupport.unpark(thread);<br>    TimeUnit.SECONDS.sleep(3);<br>    log.info("线程启动后进入sleep状态, 状态为: {}", thread.getState());<br>    synchronized (ThreadTest.class) {<br>        // 前面sleep了4秒, 5到7秒main线程持有锁.<br>        // 子线程第6秒开始获取锁, 但需要等待main线程释放锁, 此时子线程是BLOCKED状态<br>        TimeUnit.SECONDS.sleep(3);<br>        log.info("线程等待锁, 状态为: {}", thread.getState());<br>    }<br>    cyclicBarrier.await();<br>    log.info("线程已经执行结束, 状态为: {}", thread.getState());<br>}</code> 
Copy after login

The execution result is

<code>- 线程创建还未启动, 状态为: NEW<br>- 线程已经启动, 状态为: RUNNABLE<br>- 线程已经park, 状态为: WAITING<br>- 线程启动后进入sleep状态, 状态为: TIMED_WAITING<br>- 线程等待锁, 状态为: BLOCKED<br>- 线程已经执行结束, 状态为: TERMINATED</code>
Copy after login

Thread state conversion

Next we To avoid cumbersome flow charts, simply describe the mutual conversion of thread states.

  1. new can be converted to runnable

  2. runnable may be converted to blocked Or waiting, one of timed_waiting

  3. ##blocked or waiting, timed_waiting state can be converted to runnable after the conditions are met

  4. After the thread has completed execution , enter the terminated state

The above is the detailed content of Java thread status and its meaning. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template