线程一共有六种状态
1. NEW - 新建
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread t = new Thread(() -> {
System.out.println("running");
}, "t1");
System.out.println(t.getState()); // 线程创建
}
2. RUNNABLE - 可执行
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread t = new Thread(() -> {
System.out.println("running");
}, "t1");
System.out.println(t.getState()); // 线程创建
t.start();
System.out.println(t.getState()); // 执行start()
}
3. BLOCKED- 阻塞
public static void main(String[] args) throws ExecutionException, InterruptedException {
Object LOCK = new Object();
Thread t = new Thread(() -> {
System.out.println("before sync");
synchronized (LOCK) {
System.out.println("in sync");
}
}, "t1");
System.out.println(t.getState()); // 线程创建
t.start();
synchronized (LOCK) {
System.out.println("running");
Thread.sleep(3000);
}
System.out.println(t.getState()); // 执行start()
}
4. WAITING - 等待
public static void main(String[] args) throws ExecutionException, InterruptedException {
ObjectLOCK = new Object();
Thread t = new Thread(() -> {
synchronized (LOCK) {
try {
LOCK.wait();
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "t1");
System.out.println(t.getState()); // 输出:NEW 线程创建
t.start();
Thread.sleep(1000);
System.out.println(t.getState());
}
5. TIMED_WAITING - 计时等待
public static void main(String[] args) throws ExecutionException, InterruptedException {
Object LOCK = new Object();
Thread t = new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "t1");
System.out.println(t.getState()); // 输出:NEW 线程创建
t.start();
Thread.sleep(1000);
System.out.println(t.getState());
}
6. TERMINATED - 死亡
public static void main(String[] args) throws ExecutionException, InterruptedException {
Object LOCK = new Object();
Thread t = new Thread(() -> {}, "t");
System.out.println(t.getState()); // 输出:NEW 线程创建
t.start();
Thread.sleep(1000); // 让线程t执行完
System.out.println(t.getState());
}