张孝祥java多线程视频笔记----传统线程互斥技术

来源:互联网 发布:算法设计与分析第五章 编辑:程序博客网 时间:2024/05/20 14:18
//子线程循环10次,接着主线程循环100次,接着在子线程循环10次,接着再主线程循环100次
public class SynTest {


public static void main(String[] args) {
final Business b=new Business();
new Thread(
new Runnable(){


@Override
public void run() {
for(int i=1;i<=50;i++){
b.sub();
}
}

}).start();
new Thread(
new Runnable(){


@Override
public void run() {
for(int i=1;i<=50;i++){
                        b.main();
}
}

}).start();


}


}
class Business {
private boolean flag=true;
public synchronized void sub(){
while(!flag){//用while防止假唤醒
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread:"+j);
}
flag=false;
this.notify();
}
public synchronized void main(){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread:"+j);
}
flag=true;
this.notify();
}
}