java多線程――線程間通信之線程等待喚醒機制
來源:程序員人生 發布時間:2015-04-20 08:04:55 閱讀次數:3566次
- 3個方法
wait()
notify()
notifyAll()
3個方法都使用在同步中,由于要對持有鎖(又叫監控)的線程操作。
所以要使用在同步中,由于只有同步才具有鎖。
- 為何這些操作線程的方法均出現在Object類中?
由于這些方法在操作同步中的線程時候,都必須要標識所操作線程識有鎖。只有同1個鎖上的被等待的線程,可以被同1個鎖上的notify喚醒,不可以對不同鎖中的線程進行喚醒。
也就是說,等待和喚醒必須是同1個鎖。
public class Demo1 {
public static void main(String[] args) {
Res res = new Res();
Input i = new Input(res);
Output o = new Output(res);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
class Res {
private String name;
private String gender;
private boolean flag;
public synchronized void setNameGender(String name, String gender) {
if (flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = name;
this.gender = gender;
this.flag = true;
this.notify();
}
public synchronized void out() {
if (!this.flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + " : " + this.gender);
this.flag = false;
this.notify();
}
}
class Input implements Runnable {
private Res res;
Input(Res res) {
this.res = res;
}
public void run() {
int x = 0;
while (true) {
if (x % 3 == 0) {
res.setNameGender("T-mac", "male");
} else if (x % 3 == 1) {
res.setNameGender("麥迪", "男人");
} else {
res.setNameGender("CBA", "糟");
}
x++;
}
}
}
class Output implements Runnable {
private Res res;
Output(Res res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈