wait与notify的简单使用

1.子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
思路: 子线程循环10次,循环50次 ,然后主线程循环100次,循环50次,再通过wait,notify来协调子线程与主线程执行的顺序
总结
* 1.多线程问题简化为单线程问题(线程各自都做了什么),通过多线程的wait,notify等通讯关键字协调两个线程的执行顺序,并且因为子线程与主线程需要共用锁(竞争资源同一个Loop对象),我们最好将两个方法写在同一个类中,利于我们给其加锁,以及控制,也利于扩展和功能的整合.
* 2.wait ,notify 使用时一定要用while 来进行2次确认,防止伪唤醒情况的出现

public class WaitNotifyTest {
public static void main(String[] args) {
new WaitNotifyTest().init();
}

public void init(){
    final Loop loop=new Loop();
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i <50 ; i++) {
                loop.son(i);
            }
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i <50 ; i++) {
                loop.parent(i);
            }
        }
    }).start();

}
class Loop{

    private Boolean flag=true;

    public synchronized void son(int i){
            try {
                while (!flag){
                this.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int j = 0; j < 10; j++) {
                System.out.println("son time of "+j+" loop of "+i);
            }
            flag=false;
            this.notify();
    }
    public synchronized void parent(int i){
            try {
                while (flag){
                    this.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        for (int j = 0; j < 100; j++) {
            System.out.println("parent time of "+j+" loop of "+i);
        }
        flag=true;
        this.notify();
    }
}

}
欢迎大牛视察原文基地—罂粟花以及原文 http://www.poppyflower.cn/?p=108

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱飞的笨鸟

如果帮到了你,是我最大的荣幸

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值