Java中线程的状态

简介: Java中线程的状态

文章目录

1.线程的状态

本文以java1.8为例,存在类java.lang.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;

   }

2.程序状态的模拟

2.1 NEW

线程没有启动之前的状态.

@Test

   public void New() throws InterruptedException {

       Thread t1 = new Thread(()->{

           System.out.println("2:"+Thread.currentThread().getState());

       });

       System.out.println("1:"+t1.getState());

       t1.start();

       t1.join();

       System.out.println("3:"+t1.getState());

   }

输出结果:

1:NEW

2:RUNNABLE

3:TERMINATED

2.2 RUNNABLE

等待其他来自操作系统如处理器的状态。

例子如上。

2.3 BLOCKED

线程在等待锁的监控锁的状态,synchronized代码块或者方法。

public void Bolocked() throws InterruptedException {

       final Object o = new Object();

       Thread t1 = new Thread(()->{

           synchronized (o){

               try {

                   System.out.println("t1申请到了锁....");

                   TimeUnit.SECONDS.sleep(2);

               } catch (InterruptedException e) {

                   throw new RuntimeException(e);

               }

           }

       });

       new Thread(()->{

           synchronized (o) {

               try {

                   TimeUnit.SECONDS.sleep(5);

               } catch (InterruptedException e) {

                   throw new RuntimeException(e);

               }

           }

       }).start();

       TimeUnit.SECONDS.sleep(1);

       t1.start();

       TimeUnit.SECONDS.sleep(1);

       System.out.println("t1:"+t1.getState());

   }

输出状态

t1:BLOCKED

2.4 WAITING

调用以下方法的时候


{@link Object#wait() Object.wait} with no timeout

{@link #join() Thread.join} with no timeout

{@link LockSupport#park() LockSupport.park}

@Test

   public void Waiting() throws InterruptedException {

       final Lock lock = new ReentrantLock();

       Thread t1 = new Thread(()->{

           lock.lock();

           System.out.println("t1申请到了锁....");

           try {

               TimeUnit.SECONDS.sleep(2);

           } catch (InterruptedException e) {

               throw new RuntimeException(e);

           }

           lock.unlock();

       });

       new Thread(()->{

          lock.lock();

           try {

               TimeUnit.SECONDS.sleep(5);

           } catch (InterruptedException e) {

               throw new RuntimeException(e);

           }

          lock.unlock();

       }).start();

       TimeUnit.SECONDS.sleep(1);

       t1.start();

       TimeUnit.SECONDS.sleep(1);

       System.out.println("t1:"+t1.getState());

   }

输出打印结果:

t1:WAITING

2.5 TIMED_WAITING

{@link #sleep Thread.sleep}

{@link Object#wait(long) Object.wait} with timeout

{@link #join(long) Thread.join} with timeout

{@link LockSupport#parkNanos LockSupport.parkNanos}

{@link LockSupport#parkUntil LockSupport.parkUntil}

@Test

   public void TIMED_WAITING() throws InterruptedException {

       Thread t1 = new Thread(() -> {

           LockSupport.park();

           try {

               TimeUnit.SECONDS.sleep(5);

           } catch (InterruptedException e) {

               throw new RuntimeException(e);

           }

       });

       t1.start();

       SleepHelper.sleepSeconds(1);

       System.out.println("1: " + t1.getState());

       LockSupport.unpark(t1);

       TimeUnit.SECONDS.sleep(1);

       System.out.println("2: " + t1.getState());

   }

输出结果

1: WAITING

2: TIMED_WAITING

相关文章
|
3天前
|
Java 数据库
【Java多线程】对线程池的理解并模拟实现线程池
【Java多线程】对线程池的理解并模拟实现线程池
12 1
|
1天前
|
Java
Java一分钟:线程协作:wait(), notify(), notifyAll()
【5月更文挑战第11天】本文介绍了Java多线程编程中的`wait()`, `notify()`, `notifyAll()`方法,它们用于线程间通信和同步。这些方法在`synchronized`代码块中使用,控制线程执行和资源访问。文章讨论了常见问题,如死锁、未捕获异常、同步使用错误及通知错误,并提供了生产者-消费者模型的示例代码,强调理解并正确使用这些方法对实现线程协作的重要性。
9 3
|
1天前
|
安全 算法 Java
Java一分钟:线程同步:synchronized关键字
【5月更文挑战第11天】Java中的`synchronized`关键字用于线程同步,防止竞态条件,确保数据一致性。本文介绍了其工作原理、常见问题及避免策略。同步方法和同步代码块是两种使用形式,需注意避免死锁、过度使用导致的性能影响以及理解锁的可重入性和升级降级机制。示例展示了同步方法和代码块的运用,以及如何避免死锁。正确使用`synchronized`是编写多线程安全代码的核心。
12 2
|
1天前
|
安全 Java 调度
Java一分钟:多线程编程初步:Thread类与Runnable接口
【5月更文挑战第11天】本文介绍了Java中创建线程的两种方式:继承Thread类和实现Runnable接口,并讨论了多线程编程中的常见问题,如资源浪费、线程安全、死锁和优先级问题,提出了解决策略。示例展示了线程通信的生产者-消费者模型,强调理解和掌握线程操作对编写高效并发程序的重要性。
10 3
|
1天前
|
安全 Java
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第11天】在Java并发编程中,线程安全和性能优化是两个重要的主题。本文将深入探讨这两个方面,包括线程安全的基本概念,如何实现线程安全,以及如何在保证线程安全的同时进行性能优化。我们将通过实例和代码片段来说明这些概念和技术。
2 0
|
1天前
|
Java 调度
Java并发编程:深入理解线程池
【5月更文挑战第11天】本文将深入探讨Java中的线程池,包括其基本概念、工作原理以及如何使用。我们将通过实例来解释线程池的优点,如提高性能和资源利用率,以及如何避免常见的并发问题。我们还将讨论Java中线程池的实现,包括Executor框架和ThreadPoolExecutor类,并展示如何创建和管理线程池。最后,我们将讨论线程池的一些高级特性,如任务调度、线程优先级和异常处理。
|
2天前
|
安全 Java
【JAVA进阶篇教学】第十篇:Java中线程安全、锁讲解
【JAVA进阶篇教学】第十篇:Java中线程安全、锁讲解
|
2天前
|
安全 Java
【JAVA进阶篇教学】第六篇:Java线程中状态
【JAVA进阶篇教学】第六篇:Java线程中状态
|
2天前
|
缓存 Java
【JAVA进阶篇教学】第五篇:Java多线程编程
【JAVA进阶篇教学】第五篇:Java多线程编程
|
2天前
|
Java
【JAVA基础篇教学】第十二篇:Java中多线程编程
【JAVA基础篇教学】第十二篇:Java中多线程编程