生产消费中的死锁问题

本文探讨了在多线程环境下,生产消费问题可能导致的死锁现象。当所有线程均陷入等待状态时,系统出现死锁。为了解决这个问题,文章提供了相关的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个生产者,两个消费者,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;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值