張孝祥java多線程視頻筆記----傳統線程互斥技術

//子線程循環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();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章