如有錯誤或不妥,歡迎批評指正,謝謝
package com.newandroid.www.demo2;
/**
* 首先,注意,首先要明確,明確!:
* wait(),notify(),notifyAll(),這幾個方法只能被同步監聽鎖對象來調用,
* 即:線程們所共同操作的那個對象,而不是線程自己調用這些方法。
* 因爲這些方法都是非靜態的,所以要有線程們所共同操作的那個對象。
*
* 1.調用被操作對象的wait會使當前線程進入等待狀態,從字面可以看出是等待的意思,
* 當有線程調用被操作對象的notify或者notifyAll的方法時,再次恢復工作狀態
*
* 2.下面的簡單的demo中,標誌位flag的作用是,防止線程1和線程2同時進入wait()狀態,
* 不然就都在等待而不會工作了。
*/
public class Test3 {
static Test3 test3 = new Test3();
private boolean flag = true;
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
test3.method1();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
test3.mothod2();
}
}
}).start();
}
public synchronized void method1(){
try {
//flag爲true的時候輸出,
if (!flag){
this.wait();
}
flag = false;//將flag置爲false,是爲了方便線程2被喚醒後開始工作,不然線程2還會被wait()
System.out.println("Thread111111111111");
this.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void mothod2(){
try {
//flag爲false的時候輸出,
if(flag){
this.wait();
}
flag = true;//將flag置爲true,是爲了方便線程1被喚醒後開始工作,不然線程1還會被wait()
System.out.println("Thread2222222222222222222222222222222222222222222222");
this.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}