参考官方文档:
获取状态的方法:
Thread.getState()
枚举解释:
创建线程未启动start方法;
Thread thread = new Thread();
执行了该线程的start方法,在Java虚拟机中执行,但有可能在等待操作系统的其它资源,比如CPU;
thread.start();
当一个线程等待一个monitor锁的时候,状态为BLOCKED,比如被synchronized关键字修饰的方法或代码块,如下示例:
public class ThreadStateBlockTest implements Runnable { public static void main(String[] args) { ThreadStateBlockTest threadStateBlockTest = new ThreadStateBlockTest(); Thread thread1 = new Thread(threadStateBlockTest); thread1.start(); Thread thread2 = new Thread(threadStateBlockTest); thread2.start(); System.out.println("thread1 state: " + thread1.getState()); System.out.println("thread2 state: " + thread2.getState()); } @Override public void run() { blockMethod(); } /** * 阻塞的方法 */ private synchronized void blockMethod() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
执行结果:
thread1 state: TIMED_WAITING thread2 state: BLOCKED
线程1,2同时执行1先拿到了monitor锁进入synchronize修饰的方法,此时sleep不能立即执行完成,线程2再进入就是等待获取monitor锁,状态为BLOCKED
调用了Object.wait()方法后,当前线程会进入WAITING状态;
调用了Object.wait(time)或Thread.sleep(time)则线程会进入TIMED_WAITING;
Thread state for a terminated thread. The thread has completed execution.
线程的run方法执行结束;
如图:
新建线程后进入NEW状态,NEW只能进入RUNNABLE,RUNNABLE执行run方法结束进入TERMINATED,3个状态不可逆;
右侧为3个阻塞状态:
如果run方法遇到synchronize修饰的代码块或方法却没有取到monitor锁就进入BLOCKED状态;
BLOCKED取到monitor可以再次进入RUNNABLE状态;
RUNNABLE状态执行了obj的wait()或Thread.join()方法进入WAITING状态;
如果有其它线程唤醒调用了notify()或notifyAll()方法则再次进入RUNNABLE状态;
TIMED_WAITING同WAITING,是带time入参的的方法:sleep(time), wait(time),join(time);
wait()方法做了什么?
获取到monitor锁的线程,执行了wait方法后会放弃锁,进入等待状态;
notify()和notifyAll()?
前者唤醒一个等待的线程(无法指定,线程调度器自调度),后者唤醒所有等待的线程,然后再抢锁;
sleep(time)并不会释放锁,time超时后会继续执行;
需要说明的一点是WAITING状态可能变为BLOCKED状态,场景如官方文档里对BLOCKED状态的解释
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 Object.wait.
前半句理解就是进入synchronized代码库前等待monitor锁时为BLOCKED状态,后半句不太好理解,详细理解如下:
参考官方文档:
https://docs.oracle.com/en/ja...
--- END ---
马上关注 / 码上杂谈