前言
大家好,上一篇主要主要是对多线程的了解,以及对Thread的start方法,进行了源码的跟踪,今天我们主要来说一说其他的状态。
网络异常,图片无法展示
|
主要状态
// Thread.State 源码 public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; }
1. RUNNABLE-正在运行状态
看一下Thread源码中对Runnable的介绍
/** * 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. */ Java线程的RUNNABLE状态其实是包括了传统操作系统线程的ready和running两个状态的。
话不多说,接下来直接用一段demo来体现
public class deadLock { private final Object objectA = new Object(); private final Object objectB = new Object(); private AtomicInteger atomicInteger = new AtomicInteger(0); public void testA() throws InterruptedException { synchronized (objectA){ Thread.sleep(3000); synchronized (objectB){ System.out.println("objectB"); } } } public void testB() throws InterruptedException { synchronized (objectB){ Thread.sleep(3000); synchronized (objectA){ System.out.println("objectA"); } } } static class Thead0 implements Runnable{ private deadLock deadLock; public Thead0(deadLock deadLock) { this.deadLock = deadLock; } @Override public void run() { try { deadLock.testA(); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Thead1 implements Runnable{ private deadLock deadLock; public Thead1(deadLock deadLock) { this.deadLock = deadLock; } @Override public void run() { try { deadLock.testB(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { deadLock DeadLock = new deadLock(); Thread thread = new Thread(new deadLock.Thead0(DeadLock)); Thread thread1 = new Thread(new deadLock.Thead1(DeadLock)); thread.start(); //表示线程正在运行中 System.out.println("RUNNABLE:"+thread.getState()); thread1.start(); System.out.println("RUNNABLE:"+thread1.getState()); System.out.println("TIMED_WAITING:"+thread.getState()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("BLOCKED:"+thread.getState()); } }
这是一个死锁的例子,通过ThreadA与ThreadB互相抢占资源,造成线程的等待,通过图中我们可以根据打印出来的state,了解线程所处的阶段。
2. BLOCKED-阻塞状态
上面的demo中,A和B的资源互相抢占,在最后的时候输出state的状态是BLOCKED,处于BLOCKED状态的线程正等待锁的释放以进入同步区。
3. WAITING-等待状态
造成WAITING状态的方法
//使当前线程处于等待状态直到另一个线程唤醒它 Object.wait(); //等待线程执行完毕,底层调用的是Object实例的wait方法 Thread.join();
4. TIMED_WAITING-超时等待状态
线程等待一个具体的时间,时间到后会被自动唤醒。
//使当前线程睡眠指定时间 Thread.sleep(long) //线程休眠指定时间,使当前线程处于等待状态直到时间结束,或者调用notify方法唤醒 Object.wait(long) //等待当前线程最多执行millis毫秒,如果millis为0,则会一直执行 Thread.join(long)
5. TERMINATED-终止状态
//中断该线程 Thread.interrupt() //判断当前线程是否已经中断 Thread.interrupted() Thread.isInterrupted()
下一篇,我们先对Object.wait()进行一波分析。
带着问题我们先来思考一下
- 为什么调用Object.wait必须持有对象锁?
- Object.wait()被挂起后,是否会释放当前锁,让出CPU?
下一篇,我们再继续来图解wait()、notify()、join()方法。