线程之线程的通信

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();
}
}

 

转载于:https://www.cnblogs.com/1350995917ding/archive/2011/09/23/2185990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值