Java线程的六种状态
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
public class ThreadState {
public static void main(String[] args) throws Exception {
testTerminated();
}
public static void testNewAndRunnable() {
Thread thread = new Thread(() -> {});
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
}
public static void testBlocked() throws InterruptedException {
Object obj = new Object();
Thread thread = new Thread(() -> {
synchronized (obj) {
System.out.println("execute");
}
});
synchronized (obj) {
thread.start();
Thread.sleep(1);
System.out.println(thread.getState());
}
}
public static void testWaiting() throws Exception {
Object obj = new Object();
Thread thread = new Thread(() -> {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
Thread.sleep(500);
System.out.println(thread.getState());
}
public static void testTimedWaiting() throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread.start();
Thread.sleep(500);
System.out.println(thread.getState());
}
public static void testTerminated() throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread.start();
Thread.sleep(1000);
System.out.println(thread.getState());
}
}