Java中线程有六种状态。
使用IDEA找到Thread类,点进去,快捷键ALT + 7
查看Structure如下:
NEW
当线程对象被创建,但还没有调用start()方法时。
public static void main(String[] args) {
Thread thread = new Thread(() -> {
});
System.out.println(thread.getState()); // NEW
}
RUNNABLE
调用start()方法后的状态。在这个状态下,线程正在等待操作系统分配CPU时间片来执行,或者正在执行。
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
}
});
thread.start();
System.out.println(thread.getState()); // RUNNABLE
Thread.sleep(3000);
System.out.println(thread.getState()); // RUNNABLE
}
BLOCKED
线程被阻塞时,暂时停止执行。线程可能会进入阻塞状态,等待获取一个锁,或者等待一段时间后再次尝试获取锁。
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread t1 = new Thread(() -> {
synchronized (obj) {
}
});
synchronized (obj) {
t1.start();
System.out.println(t1.getState()); // RUNNABLE
Thread.sleep(3000);
System.out.println(t1.getState()); // BLOCKED
}
}
WAITING
当线程等待某个条件时,它进入等待状态。这个状态下,线程不会占用CPU时间片,直到条件满足。
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread t1 = new Thread(() -> {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
System.out.println(t1.getState()); // RUNNABLE
Thread.sleep(3000);
System.out.println(t1.getState()); // WAITING
}
TIMED_WAITING
和WAITING状态一样,但是不需要手动唤醒,在打到一定时间后(sleep)自动唤醒。
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
Thread.sleep(1000);
System.out.println(t1.getState()); // TIMED_WAITING
}
TERMINATED
线程结束的状态
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
System.out.println(t1.getState()); // RUNNABLE
Thread.sleep(500);
System.out.println(t1.getState()); // TIMED_WAITING
Thread.sleep(2000);
System.out.println(t1.getState()); // TERMINATED
}