Lock与Condition应用(三个线程之间通信问题)

public class ConditionCommunication {

    public static void main(String[] args) {
        final Bussiness bussiness = new Bussiness();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i < 50;i++){
                    bussiness.father(i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i < 50;i++){
                    bussiness.grandson(i);
                }
            }
        }).start();

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

    }

    static class Bussiness{
        private static int qu = 1;
        Lock lock = new ReentrantLock();
        Condition father = lock.newCondition();
        Condition son = lock.newCondition();
        Condition grandson = lock.newCondition();
        public void father(int i){
            lock.lock();
            try{
                while(qu != 1){
                        father.await();
                }
                for(int j = 0;j < 10;j++)
                    System.out.println("第" + i + "次循环=============" + "father线程第" + j + "次循环");
                qu = 2;
                son.signal();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }

        public void son(int i){
            lock.lock();
            try{
                while(qu != 2){
                    son.await();
                }
                for(int j = 0;j < 20;j++){
                    System.out.println("第" + i + "次循环=============" + "son线程第" + j + "次循环");
                }
                qu = 3;
                grandson.signal();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }

        public void grandson(int i){
            lock.lock();
            try{
                while(qu != 3){
                    grandson.await();
                }
                for(int j = 0;j < 20;j++){
                    System.out.println("第" + i + "次循环=============" + "grandson线程第" + j + "次循环");
                }
                qu = 1;
                father.signal();
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值