利用wait notify 实现线程互斥通知

来源:互联网 发布:性喜剧 知乎 编辑:程序博客网 时间:2024/06/16 09:57
public class TestWaitNotifyMutex {


boolean isF1 = true;

public static void main(String[] args) {
final TestWaitNotifyMutex twnm = new TestWaitNotifyMutex();
new Thread(){
public void run() {
twnm.f1();
};
}.start();
new Thread(){
public void run() {
twnm.f2();
};
}.start();
}

private synchronized void f1(){

try {
while(isF1){
System.out.println("111111");
isF1 = false;
notifyAll();
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void f2(){

try {
while(!isF1){
System.out.println("222222");
isF1 = true;
notifyAll();
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
0 0
原创粉丝点击