Thread定义的线程状态
在Thread类中定义了线程状态枚举类
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
1. NEW: A thread that has not yet started in this state.
2. RUNNABLE: A thread executing in the java virtual machine is in the state.
3. BLOCKED: A thread that is blocked waiting for a monitor lock is in the state.
4. WAITING: A thread that is waiting indefinitely(无限) for another thread to perform a particular action is in the state.
5. TIMED_WAITING:A thread that is waiting for another thread to perform an action for up to a specified waiting time is in the state.
6. TERMINATED: A thread that has exited is in the state.
getState
方法,获取到该线程的状态,从代码中可以看到线程的状态是由JVM决定的
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
生命周期的状态
一般将BLOCKED,WAITING,TIMED_WAITING都成为阻塞
代码演示示例,通过控制时间来观察线程的状态
public class ThreadStateMain {
public static void main(String[] args) throws Exception{
// 观察线程1的周期函数
Thread one = new Thread(()-> {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
;
}
try {
System.out.println("进入时间等待");
Thread.sleep(1000);
} catch (InterruptedException e) {
//
}
// 访问方法
rvn();
});
// 主要用户代码块的访问
Thread two = new Thread(()->rvn());
// 线程2启动获取锁
two.start();
System.out.println("执行之前的状态:"+one.getState());
one.start();
System.out.println("执行中的状态:"+one.getState());
Thread.sleep(500);
System.out.println("线程进入时间等待:"+one.getState());
Thread.sleep(1000);
System.out.println("线程进入synchronized等待:"+one.getState());
Thread.sleep(8000);
System.out.println("执行完成: "+one.getState());
}
public static synchronized void rvn() {
try {
Thread.sleep(6000);
}catch (InterruptedException e){
//
}
}
}
/**
执行之前的状态:NEW
执行中的状态:RUNNABLE
进入时间等待
线程进入时间等待:TIMED_WAITING
线程进入synchronized等待:BLOCKED
执行完成: TIMED_WAITING
*/
在编写上面代码的过程中,我发现,线程的启动执行,它的时间点是不确定的,在众多线程启动并且在不确定的时间点下进入不同的状态,执行不同的代码,操作访问不同的资源,我想,这应该是多线程编程的难点所在。