JAVA生产者消费者问题

某技术群里群友抛出这样一个问题,我觉得挺有意思就写了一下。题目如下:
请添加图片描述
其实本质是一个生产者消费者问题,只不过他要求一共十个线程,id为奇数的是存钱,id为偶数的取钱。代码如下 可以直接运行。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class SyncMoney implements Runnable {

    private int money = 0;
    private List<Thread> threadList = new ArrayList<Thread>();
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public SyncMoney() {
        for (int i = 1; i <= 10; i++) {
            Thread thread = new Thread(this);
            threadList.add(thread);
            thread.start();
        }
    }

    /**
     * 存钱,每次money++
     */
    private synchronized void put() {
        money++;
        System.out.println(Thread.currentThread().getId() + ":存钱,余额" + money);
        //暂停一会
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (money > 10) {
            this.notify();
        }
    }

    /**
     * 取钱,每次money--。money不足10等待
     *
     * @throws InterruptedException
     */
    private synchronized void get() {
        while (money <= 10) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //暂停一会
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        money--;
        System.err.println(Thread.currentThread().getId() + ":取钱,余额" + money);
    }


    /**
     * 创建十个线程,启动任务
     */
    public void start() {
        countDownLatch.countDown();
    }

    @Override
    public void run() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //奇数线程存钱,偶数线程取钱
        long id = Thread.currentThread().getId();
        if (id % 2 != 0) {
            while (true) {
                this.put();
            }
        } else {
            while (true) {
                this.get();
            }
        }
    }

    public static void main(String[] args) {
        SyncMoney syncMoney = new SyncMoney();
        syncMoney.start();
    }
}

运行结果如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值