线程间通信 wait() notify()

线程间通过锁对象进行同步,将锁加在多个线程共同访问的资源上,实现多个线程的同步

线程间  可以通过 notify(),notifyAll(),wait()方法进行调度,wait()必须用在同步代码块或同步方法里,锁对象调用wait()后,释放同步方法锁,给其他具有同等优先级,或者更高优先级的线程执行,


public class TraditionalThreadCommunication {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(new Runnable() {


@Override
public void run() {
for (int m = 0; m < 50; m++) {
bussiness.sub(m);
}
}
}).start();
for (int m = 0; m < 50; m++) {
bussiness.main(m);
}
}
}


class Bussiness {
private boolean bShouldSub = true;


public synchronized void main(int m) {
//为什么不用if,而用while
//防止伪同步,有时候线程wait()了也自动唤醒会执行,这时while判断,

while (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 100; i++) {
System.out.println("main thread sequence of" + i+"of loop "+m);
}
bShouldSub = false;
this.notify();
}


public synchronized void sub(int m) {
while (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("sub thread sequence of" + i+ "of loop "+m);
}
bShouldSub = true;
this.notify();
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值