生产消费中的死锁问题
来源:互联网 发布:mac sdk 配环境变量 编辑:程序博客网 时间:2024/05/01 11:11
一个生产者,两个消费者,MAX=1,
有一个时刻,所有的线程都进入等待队列。
解决死锁问题,见以下代码:
package java.thread;/** * 生产消费中的死锁问题 */public class ThreadDemo6 {public static void main(String[] args) {//使用java中集合类,List是列表。Pool1 pool = new Pool1();Productor p1 = new Productor("生产者1", pool);p1.setName("p1");Consumer1 c1 = new Consumer1("消费者", pool);c1.setName("c1");Consumer1 c2 = new Consumer1("消费者", pool);c2.setName("c2");p1.start();c1.start();c2.start();}}//生产者class Productor extends Thread {static int i = 0;private String name;private Pool1 pool;public Productor(String name, Pool1 pool) {this.name = name;this.pool = pool;}public void run() {while (true) {pool.add(i++);}}}//消费者class Consumer1 extends Thread {private String name;private Pool1 pool;public Consumer1(String name, Pool1 pool) {this.name = name;this.pool = pool;}public void run() {while (true) {pool.remove();//System.out.println("-: " + i);}}}/** * 池子 */class Pool1 {private java.util.List<Integer> list = new java.util.ArrayList<Integer>();//容器最大值private int MAX = 1;//添加元素public void add(int n) {synchronized (this) {try {String name = Thread.currentThread().getName();while (list.size() == MAX) {System.out.println(name + ".wait()");//限时等待。this.wait();}list.add(n);System.out.println(name + " + : " + n);System.out.println(name + ".notify()");this.notifyAll();} catch (Exception e) {e.printStackTrace();}}}//删除元素public int remove() {synchronized (this) {try {String name = Thread.currentThread().getName();while (list.size() == 0) {System.out.println(name + ".wait()");this.wait();}int i = list.remove(0);System.out.println(name + " - : " + i);System.out.println(name + ".notify()");this.notifyAll();return i;} catch (Exception e) {e.printStackTrace();}return -1;}}}
阅读全文
0 0
- 生产消费中的死锁问题
- 多线程生产消费问题
- 线程---生产消费问题
- 生产消费问题
- java生产消费问题
- 实例代码摘录_生产消费、死锁
- 线程 --生产和消费问题
- Java模拟生产消费问题
- 生产消费问题整合版
- 多线程之生产消费问题
- 生产消费
- 生产消费
- 条件变量实现生产消费问题
- java多线程之生产消费问题
- 多线程中多生产多消费问题
- AutoResetEvent来模拟实现生产消费问题
- 【Java】----线程同步:生产-消费问题
- Java 线程同步 生产消费问题
- Android编程历程之Android布局文件模块化
- Android属性动画之ValueAnimator
- XZ_iOS之函数式编程和链式编程
- Java 错误:找不到或无法加载主类(源文件中含有包名 package)
- Vue.js 组件和组件通信
- 生产消费中的死锁问题
- 判断二叉树是否为完全二叉树
- 【PAT甲级】1079. Total Sales of Supply Chain (25)
- 7.30小记
- bash: 一键安装Ananconda & 一键设置conda永久镜像
- hdu 6052单调栈 双指针
- CSS深入理解(1)margin
- DPDK 内存管理(二)(rte_mempool 内存管理)
- 模拟实现atoi函数