首先製作一個物件方便觀察執行續狀態:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class ThreadState implements Runnable { public synchronized void waitForASecond() throws InterruptedException { wait(500); } public synchronized void waitForYears() throws InterruptedException { wait(); } public synchronized void notifyNow() { notify(); } @Override public void run() { // TODO Auto-generated method stub try { waitForASecond(); waitForYears(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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()); } } |
文章標籤
全站熱搜