线程的状态
线程由六种状态,分别是,NEW(new)
、 RUNNABLE(runnable)
、 TERMINATED(terminated)
、 WAITING(waiting)
、TIMED_WAITING(timed_waiting)
、 BLOCKED(blocked)
NEW(new)
:线程对象已存在,但是还没有在内核中创建。
RUNNABLE(runnable)
:线程处于运行状态或随时可以调度到CPU上运行。
TERMINATED(terminated)
:内核中的线程结束并销毁,但是线程对象还存在。
WAITING(waiting)
:死等
TIMED_WAITING(timed_waiting)
:带有时间的等待。
BLOCKED(blocked)
:锁控制(后续介绍)。
- NEW
public class Demo14 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
});
System.out.println(t.getState());
// NEW:线程对象已存在,但是还没有在内核中创建。
}
}
- RUNNABLE(runnable)
public class Demo14 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
});
t.start();
System.out.println(t.getState());
// RUNNABLE(runnable):线程处于运行状态或随时可以调度到CPU上运行。
}
}
- TERMINATED(terminated)
public class Demo14 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
});
t.start();
t.join();
System.out.println(t.getState());
// TERMINATED(terminated):内核中的线程结束并销毁,但是线程对象还存在。
}
}
- WAITING(waiting)
public class Demo13 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
System.out.println("thread-0");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"thread-0");
Thread t1 = new Thread(() -> {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("thread-1");
}
},"thread-1");
t.start();
t1.start();
t.join();
t1.join();
System.out.println(t.getState()); // t1 线程死等 t 线程
// 死等(waiting),t1 线程死等 t 线程;同时,main线程死等 t 和 t1 两个线程
}
}
- TIMED_WAITING(timed_waiting)
public class Demo13 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
System.out.println("thread-0");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"thread-0");
Thread t1 = new Thread(() -> {
try {
t.join(200000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("thread-1");
}
},"thread-1");
t.start();
t1.start();
t.join(100000);
t1.join(200000);
System.out.println(t.getState());
// 等待一段时间
}
}