线程互斥通信

1.子线程运行10次,主线程运行20次,接着回到子线程10次,然后在是主线程20次,如此循环10次。

** 当要用到共同数据(包括同步锁)的若干方法应当放在同一个类当中,体现了程序的高类聚,和健壮性。
public class Test{
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
public void run() {
for(int i=1;i<=10;i++){
business.son();
}
}
}).start();

for(int i=1;i<=10;i++){
business.main();
}
}
}

class Business{
boolean b = true;
public synchronized void son(){
while(!b){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for(int j = 1;j<=10;j++){
System.out.println("son=>"+j);
}

b = false;
this.notify();
}

public synchronized void main(){
while (b) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for(int j = 1;j<=20;j++){
System.out.println("main=>"+j);
}

b = true;
this.notify();
}
}

posted @ 2016-03-08 22:46  ysw  阅读(130)  评论(0编辑  收藏  举报