Oracle JDK 定义中,线程一共有六种状态
NEW:未启动状态
Thread t= newThread() {
@Overridepublic voidrun() {
System.out.println(Thread.currentThread().getName());
}
};
System.out.println(t.getState().name());
RUNNABLE:可运行状态
处于可运行状态的线程正在 Java 虚拟机中执行,但也可能是正在等待来自操作系统资源,例如 CPU。
Thread t= newThread() {
@Overridepublic voidrun() {
System.out.println(Thread.currentThread().getName());
}
};
t.start();
System.out.println(t.getState().name());
BLOCKED:阻塞状态
final Object lock = newObject();
Thread t= newThread() {
@Overridepublic voidrun() {synchronized(lock) {
System.out.println(Thread.currentThread().getName());
}
}
};synchronized(lock) {try{
t.start();
Thread.sleep(1000);
System.out.println(t.getState().name());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
WAITING:等待状态
调用以下方法,使线程处于等待状态:
Object.wait()、Thread.join()、LockSupport.park()
另一个线程调用以下方法,使线程继续执行:
notify() 是随机唤醒的,不同的 JDK 版本,在等待队列中唤醒的线程,其位置在等待队列中不同。
JDK1.8 中 notify() 唤醒的是等待队列中的头节点(等待时间最长的那个线程)
Object.notify()、 Object.notifyAll()、Thread.join()、LockSupport.unpark(Thread)
final Object lock = newObject();
Thread t= newThread() {
@Overridepublic voidrun() {try{synchronized(lock) {
lock.wait();
System.out.println(Thread.currentThread().getName());
}
}catch(InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}synchronized(lock) {
System.out.println(t.getState().name());
lock.notifyAll();
}
TIMED_WAITING:具有指定时间的等待状态
调用以下方法,使线程处于指定时间的等待状态:
Thread.sleep()、Object.wait()、Thread.join()、LockSupport.parkNanos()、LockSupport.parkUntil()
Thread t = newThread() {
@Overridepublic voidrun() {try{
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState().name());
TERMINATED:已终止线程的线程状态或线程已完成执行
Thread t = newThread() {
@Overridepublic voidrun() {
System.out.println(Thread.currentThread().getName());
}
};
t.start();try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState().name());
线程的状态图