1.需求:
子線程迴圈10次,主線程迴圈100次,這樣間隔迴圈50次. 2.實現:
package com.amos.concurrent;/** * @ClassName: ThreadSynchronizedConnect * @Description: 用wait,notify實現線程間的通訊,需求:子線程迴圈10次,主線程迴圈100次,這樣間隔迴圈50次. * @author: amosli * @email:hi_amos@outlook.com * @date Apr 20, 2014 4:39:44 PM */public class ThreadSynchronizedConnect { public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 50; i++) { business.sub(i); } } }).start(); for (int i = 0; i < 50; i++) { business.main(i); } } /* * 經驗:要用到共同資料(包括同步鎖)的若干方法,應該歸在同一個類身上,這樣方便實現,高類聚和程式的健狀性上. */ static class Business { private boolean is_sub = true; //子方法 public synchronized void sub(int i) { while (!is_sub) {//如果不為true,將等待,Blocked狀態 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("sub thread:" + j + " loop:" + i); } is_sub=false; this.notify();//喚醒正在等待的線程 } //主方法 public synchronized void main(int i) { while (is_sub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 100; j++) { System.out.println("main thread:" + j + " loop:" + i); } is_sub=true; this.notify(); } }}
3.註解:
這裡要注意的是如果要用到共同資料(包括同步鎖)的若干方法,應該歸在同一個類身上.
1).從線程的四種狀態之間的轉換圖可能看到,將一個線程從可運行狀態轉為阻塞狀態只需要調用wait()方法,即將線程加入到等待狀態.
2).然後將等待中的狀態喚醒只需要調用notify()方法即可,如果要喚醒所有等待中的線程,可以調用notifyall()方法.
3)使用synchronized關鍵字來同步方法,使其在運行時不受影響.