兩個線程公用一個Object對象,監控線程先調用Object的wait(),添加線程執行插入,插入之后調用Object的notify()
如此反復
在run方法里加鎖synchronizide,同時在鎖的內部使用wait方法和notify方法使用就ok了
public class ThreadTest2 { public static void main(String[] args) { // 創建任務 // 任務一: 讀取數據庫,給對象賦值 Person p = new Person(); Input input = new Input(p); // 任務二:將對象的數據取出,保存到數據中 Output output = new Output(p); // 創建線程,一個線程讀取數據. Thread t1 = new Thread(input); // 創建線程,一個線程寫出數據 Thread t2 = new Thread(output); t1.start(); t2.start(); } } /** * 該任務模擬讀取信息並使用對象存儲讀取的數據. * */ class Input implements Runnable { Person p; Input(Person p) { this.p = p; } int i = 0; /** * 通過循環,模擬線程不停的從數據庫中讀取數據,並給對象賦值. */ public void run() { while (true) { if (i % 2 == 0) { p.write("jack", "male"); } else { p.write("麗麗", "女"); } i++; } } } /** * 該任務定義讀取對象中的數據,並寫出到數據庫中. */ class Output implements Runnable { Person p; Output(Person p) { this.p = p; } /** * 模擬不停=取出對象的數據,並保存到數據中. */ public void run() { while (true) { p.read(); } } } class Person { private String name; private String gender; // flag 表示開關,默認是斷開 boolean flag = false; public synchronized void write(String name, String gender) { // 當開關是斷開的時候,該線程給對象賦值. if (!flag) { this.name = name; this.gender = gender; // 給對象賦值完畢,需要將開關關閉. flag = true; notify(); // 線程喚醒機制.喚醒線程. // 讓Input線程給對象賦值完數據,該線程應該等待,不能再執行. try { this.wait(); // 可以讓當前Input 線程等待. 等待Output 讀取對象數據. } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * <pre> * 使用了wait 和notify 方法,實現了線程的通信. * wait() 線程等待. 釋放cpu ,釋放鎖 * notify() 喚醒線程. * </pre> * */ public synchronized void read() { // 如果開關是關閉,讀取對象的數據. if (flag) { System.out.println(this.name + "---" + this.gender); // 取完對象的數據,修改開關,將開關斷開. flag = false; // 喚醒線程 notify(); // 線程Output 將對象的數據讀取完畢后,也應該等待,等待Input再次給對象賦值. try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }