多生产者-消费者中假死现象的处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ditto_zhou/article/details/80239258

单个的生产者-消费者模型

package com.ftf.thread.lock;

public class Factory {
	private volatile boolean flag = true;
	private Object obj = new Object();
	public void setValue(){
		synchronized (obj) {
			try {
			while(!flag){
					obj.wait();
			}
			System.out.println("生产者生产数据......");
			Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			flag = false;
			obj.notify();
		}
	}
	public void getValue(){
		synchronized (obj) {
			try {
			while(flag){
				obj.wait();
			}
			System.out.println("消费者消费数据....");
			Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			flag = true;
			obj.notify();
		}
	}
	public static void main(String[] args) {
		final Factory ft = new Factory();
		Thread product = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					ft.setValue();
				}
			}
		});
		Thread customer = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					ft.getValue();
				}
			}
		});
		customer.start();
		product.start();
	}
}

但是如果,多启动一个生产者消费者,或者生产者线程,就会出现线程假死现象,生产者/消费者线程不在执行。

public static void main(String[] args) {
		final Factory ft = new Factory();
		Thread product = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					ft.setValue();
				}
			}
		});
		Thread customer = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					ft.getValue();
				}
			}
		});
		Thread customer1 = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					ft.getValue();
				}
			}
		});
		Thread customer2 = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					ft.getValue();
				}
			}
		});
		customer1.start();
		customer2.start();
		customer.start();
		product.start();
	}

结果:


原因:在于notify在多生产-多消费者情况下,唤醒的可能是同类,导致生产者或消费者线程没有竞争锁的机会,出现假死,

解决:notify改为notifyAll,如果使用的是lock锁的话,多生产者消费者模型中,使用signalAll来解决假死现象

没有更多推荐了,返回首页