当前位置: 首页 > news >正文

笔试,猴子吃香蕉,多线程写法

package demo;import java.util.concurrent.CountDownLatch;/*** @description: 猴子吃香蕉* @author: wxm* @create: 2023-10-23 14:01**/
public class Main {public static void main(String[] args) throws InterruptedException {Monkey[] m = new Monkey[3];Resource r = new Resource();for (int i = 0; i < 3; i++) {m[i] = new Monkey(r);}for (int i = 0; i < 3; i++) {int j = i;new Thread(()->m[j].add()).start();}r.latch.await();for (int i = 0; i < 3; i++) {System.out.println(i +" " + m[i].count);}}}class MyThread extends Thread{Monkey monkey;public MyThread(Monkey monkey){this.monkey = monkey;}@Overridepublic void run(){monkey.add();}
}class Monkey{Resource resource;int count;public Monkey(Resource resource){this.resource = resource;this.count = 0;}public void add(){try {while (true){if(resource.consumer()) count++;else break;}}finally {resource.latch.countDown();}}}class Resource{private volatile int num = 10000;public CountDownLatch latch = new CountDownLatch(3);public synchronized boolean consumer(){if (num == 0) return false;num--;return true;}}
http://www.lryc.cn/news/204760.html

相关文章:

  • 安装docker ,更换docker版本
  • 英语小作文写作模板及步骤(1)
  • 编写hello驱动程序
  • ZYNQ中断例程
  • 常用linux命令 linux_cmd_sheet
  • 【proteus】8086 写一个汇编程序并调试
  • 大数据之LibrA数据库常见术语(四)
  • Docker基础知识
  • swoole 是什么?
  • 我想要一个勋章
  • 微信小程序设计之主体文件app-json-pages
  • C语言-面试题实现有序序列合并
  • Android12 启动页适配
  • 【微服务保护】初识 Sentinel —— 探索微服务雪崩问题的解决方案,Sentinel 的安装部署以及将 Sentinel 集成到微服务项目
  • 20231023 比赛总结
  • Vite创建vue3+ts+pinia+vant项目起步流程
  • JVM 类的加载子系统
  • 什么是1024程序员节
  • spark获取hadoop服务token
  • Simulink 最基础教程(一)
  • 微信小程序:单行输入和多行输入组件
  • 1024程序员
  • 【Segment Anything Model】八:修改SAM源码做分类任务
  • Java后端开发——实现登录验证程序
  • CSS高频面试题
  • 解决matlab报错“输入参数的数目不足”
  • 使用python_opencv比较图像差异/使用python_opencv找出两张图像的差异范围
  • NOIP2023模拟1联测22 爆炸
  • http post协议实现简单的rpc协议,WireShark抓包分析
  • 1024程序员节