一、线程状态
线程状态分为以下几种: New:新创建的线程,尚未执行; Runnable:运行中的线程,正在执行run()方法的Java代码; Blocked:运行中的线程,因为某些操作被阻塞而挂起(如等待获取锁); Waiting:运行中的线程,因为某些操作在等待中(如join(),wait()); Timed Waiting:运行中的线程,因为执行sleep()方法正在计时等待; Terminated:线程已终止,因为run()方法执行完毕。
可以通过Thread的getState()方法获得线程当前状态
二、示例
代码如下(示例):
public class First extends Thread{
public static void main(String[] args) throws InterruptedException{
Thread t = new First();
Thread tt = new Thread(()->{
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("线程状态:"+tt.getState());
tt.start();
System.out.println("线程状态:"+tt.getState());
Thread.sleep(1000);
System.out.println("线程状态:"+tt.getState());
tt.join();
System.out.println("线程状态:"+tt.getState());
}
@Override
public synchronized void run() {
int i = 1;
while (i<3){
System.out.println(this.getName()+":打印"+i);
i++;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
线程状态:NEW
线程状态:RUNNABLE
Thread-0:打印1
Thread-0:打印2
线程状态:WAITING
线程状态:TERMINATED
2.源码阅读
如下: getState返回枚举
private volatile int threadStatus = 0;
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
public State getState() {
return sun.misc.VM.toThreadState(threadStatus);
}
public static State toThreadState(int var0) {
if ((var0 & 4) != 0) {
return State.RUNNABLE;
} else if ((var0 & 1024) != 0) {
return State.BLOCKED;
} else if ((var0 & 16) != 0) {
return State.WAITING;
} else if ((var0 & 32) != 0) {
return State.TIMED_WAITING;
} else if ((var0 & 2) != 0) {
return State.TERMINATED;
} else {
return (var0 & 1) == 0 ? State.NEW : State.RUNNABLE;
}
}
总结
如有错漏,敬请指出。
|