線程簡單的測試例子,用於瞭解線程的概念和狀態
public class ThreadState implements Runnable {
public synchronized void waitForASecond() throws InterruptedException{
wait(500);
System.out.println("我在等待5毫秒");
}
public synchronized void waitForYears() throws InterruptedException{
wait();
System.out.println("我在永久等待");
}
public synchronized void notifyNow(){
notify();
System.out.println("我被喚醒了");
}
public void run() {
try {
waitForASecond();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
waitForYears();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
ThreadState state = new ThreadState();
Thread thread = new Thread(state);
System.out.println("新建線程"+thread.getState());
thread.start();
System.out.println("啓動線程"+thread.getState());
thread.sleep(100);
System.out.println("計時等待"+thread.getState());
thread.sleep(1000);
System.out.println("等待線程"+thread.getState());
state.notifyNow();
System.out.println("喚醒線程"+thread.getState());
thread.sleep(1000);
System.out.println("終止線程"+thread.getState());
}
}
輸出:
新建線程NEW
啓動線程RUNNABLE
計時等待TIMED_WAITING
我在等待5毫秒
等待線程WAITING
我被喚醒了
我在永久等待
喚醒線程TERMINATED
終止線程TERMINATED