多线程-条件变量Condition

Java多线程

进程与线程
Java线程
线程状态的切换
同步与锁
生产者与消费者模型
锁与死锁



前言

设想一下假如我们对一个账户,进行存款与取款操作,当取款操作进行时余额不够进行等待阻塞,存款后只需要唤醒存款的线程该如何处理?


一、Condition是什么?

Condition是java.util.concurrent.locks包下面的一个接口,从包名上面看就能够看出是并发锁时候用的。
存在以下方法:
在这里插入图片描述

  1. await():当前线程进行等待,直到收到信号通知
  2. await(long,TimeUnit):在指定时间内进行等待,直到收到信号通知或者时间到达
  3. awaitUninterruptibly():支持打断,在thread上面执行interrupt方法不会报错
  4. awaitNanos(long):使当前线程等待,直到它被信号或中断,或指定的截止日期过期(入参long)
  5. awaitUntil(Date):使当前线程等待,直到它被信号或中断,或指定的截止日期过期(入参long)
  6. signal():唤醒在当前条件下面的某一个线程
  7. signalAll():唤醒在当前条件下面的所有线程

二、存款/取款示例

1.设计流程

在这里插入图片描述

2.编写代码

代码如下(示例):

public class ConditionTypeDemo {

    public static void main(String[] args) {
        //创建并发操作的账户
        MyAccount myAccount = new ConditionTypeDemo().new MyAccount("2333333333",100);
        //创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Thread t1 = new ConditionTypeDemo().new GetThread("张三", myAccount, 2000);
        Thread t2 = new ConditionTypeDemo().new SaveThread("李四", myAccount, 3600);
        Thread t3 = new ConditionTypeDemo().new SaveThread("王五", myAccount, 2700);
        Thread t4 = new ConditionTypeDemo().new SaveThread("老张", myAccount, 600);
        Thread t5 = new ConditionTypeDemo().new GetThread("老牛", myAccount, 1300);
        Thread t6 = new ConditionTypeDemo().new GetThread("胖子", myAccount, 800);
        //执行各个线程
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        //关闭线程池
        pool.shutdown();
    }


    public class MyAccount {
        //账户编号
        private String aId;
        //余额
        private int cash;
        //账号锁
        private Lock lock = new ReentrantLock();
        //存条件
        private Condition saveCondition = lock.newCondition();
        //取条件
        private Condition getCondition = lock.newCondition();
        MyAccount(String aId , int cash){
            this.aId = aId;
            this.cash = cash;
        }


        /**
         * 存款
         * @param x
         * @param name
         */
        public void saveCash(int x ,String name){
            //获取锁
            lock.lock();
            try{
                if(x>0){
                    cash+=x;
                    System.out.println(name+"存款了"+x+"元,当前余额为:"+cash);
                }
                //唤醒取条件下面的线程
                getCondition.signalAll();;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }

        public void getCash(int x , String name){
            lock.lock();
            try {
                if(cash-x<0){
                    //余额不够,阻塞取款操作
                    System.out.println(name+"余额不够,阻塞取款操作");
                    getCondition.await();
                    System.out.println(name+"被唤醒,取款操作");
                }
                cash -=x;
                System.out.println(name+"取款:"+x+"元,当前余额为:"+cash);
                saveCondition.signalAll();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }


    public class SaveThread extends Thread{
        //人
        private String name;

        private MyAccount myAccount;

        private int x;
        SaveThread(String name , MyAccount myAccount,int x){
            this.myAccount = myAccount;
            this.name = name;
            this.x = x;
        }

        @Override
        public void run(){
            myAccount.saveCash(x,name);
        }
    }

    public class GetThread extends Thread{
        //人
        private String name;

        private MyAccount myAccount;

        private int x;
        GetThread(String name , MyAccount myAccount,int x){
            this.myAccount = myAccount;
            this.name = name;
            this.x = x;
        }

        @Override
        public void run(){
            myAccount.getCash(x,name);
        }
    }
}

在这里插入图片描述

总结

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值