线程之线程的通信


复制代码
public class TraditionalCommunication {

/**
*
@param args
*/
public static void main(String[] args) {

final Bussiness bussiness = new Bussiness();

new Thread(new Runnable(){
public void run() {
for(int i=0;i<50;i++){
try {
bussiness.child();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

for(int i=0;i<50;i++){
try {
bussiness.main();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

/*
* 要上在要操作资源的内部方法上,而不是线程上
* 如果Bussiness的方法锁在线程上那么如果另外的对象再次调用时还要加锁
*
* 要用到的共同数据(包括同步锁)的若干方法应归在同一个类的身上,这种设计体现了高类聚和程序的健壮性
*/
class Bussiness{
//设置该那个线程运行
boolean isRun = true;
synchronized void child() throws InterruptedException{
//这里的判断最好是使用while,提防假唤醒
while(!isRun){
//不该当前线程运行,就调用wait
this.wait();
}
for(int i=0;i<10;i++){
System.out.println("child is running the "+(i+1)+" times ");
}
//改变值
isRun = false;
//把另一个线程唤醒
this.notify();
}

synchronized void main() throws InterruptedException{
//这里的判断最好是使用while,提防假唤醒
while(isRun){
//不该当前线程运行,就调用wait
this.wait();
}
for(int i=0;i<100;i++){
System.out.println("main is running the "+(i+1)+" times");
}
//改变值
isRun = true;
//把另一个线程唤醒
this.notify();
}
}
复制代码

 

posted @ 2014-03-15 23:54  huidaoli  阅读(134)  评论(0编辑  收藏  举报