Java的多线程模型
2021/8/25 12:06:06
本文主要是介绍Java的多线程模型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
https://blog.csdn.net/qq_40550018/article/details/87859399
//商品类 public class Goods { private int id; private String name; public Goods(int id, String name) { this.id = id; this.name = name; } } //消费者类 public class Producer implements Runnable { private Goods goods; @Override public void run() { while (true) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TestPC.queue) { goods=new Goods(1,"商品"); if (TestPC.queue.size()<MAX_POOL) { TestPC.queue.add(goods); System.out.println(Thread.currentThread().getName()+"生产商品"); } else { try { TestPC.queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } //生产者类 public class Consumer implements Runnable { @Override public void run() { while (true){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TestPC.queue){ if(!TestPC.queue.isEmpty()){ TestPC.queue.poll(); System.out.println(Thread.currentThread().getName()+"消费商品"); } else { TestPC.queue.notify(); } } } } } //测试类 public class TestPC { public static final int MAX_POOL=10; public static final int MAX_PRODUCER=5; public static final int MAX_CONSUMER=4; public static Queue<Goods> queue=new ArrayBlockingQueue<>(MAX_POOL); public static void main(String[] args) { Producer producer=new Producer(); Consumer consumer=new Consumer(); for(int i=0;i<MAX_PRODUCER;i++) { Thread threadA = new Thread(producer, "生产者线程"+i); threadA.start(); } for(int j=0;j<MAX_CONSUMER;j++) { Thread threadB = new Thread(consumer, "消费者线程"+j); threadB.start(); } } }
这篇关于Java的多线程模型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26消息中间件源码剖析教程
- 2024-11-26JAVA语音识别项目资料的收集与应用
- 2024-11-26Java语音识别项目资料:入门级教程与实战指南
- 2024-11-26SpringAI:Java 开发的智能新利器
- 2024-11-26Java云原生资料:新手入门教程与实战指南
- 2024-11-26JAVA云原生资料入门教程
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程