多线程的多消费者和多生产者signal和await

Posted windzly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程的多消费者和多生产者signal和await相关的知识,希望对你有一定的参考价值。

package test;

import java.awt.List;
import java.awt.image.AreaAveragingScaleFilter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.io.BufferedInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import javax.security.auth.callback.LanguageCallback;
import javax.swing.text.StyledEditorKit.BoldAction;

class Resourse {
	private String name;
	private boolean flag = false;
	private int count;
	Lock lock = new ReentrantLock();
	Condition proCondition = lock.newCondition();
	Condition condition = lock.newCondition();

	public void put(String name) {
		lock.lock();
		try {
			while (flag) {
				try {
					proCondition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			flag = true;
			++count;
			this.name = name + count;
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

	public void take() {
		lock.lock();
		try {
			while (!flag) {
				try {
					condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			flag = false;
			System.out.println(Thread.currentThread().getName() + " ........" + this.name);
			proCondition.signal();
		} finally {
			lock.unlock();
		}
	}
}

class Producer implements Runnable {
	Resourse r;

	Producer(Resourse r) {
		this.r = r;
	}

	@Override
	public void run() {
		while (true) {
			r.put("烤鸭");
		}
	}

}

class Consumer implements Runnable {
	Resourse r;

	Consumer(Resourse r) {
		this.r = r;
	}

	@Override
	public void run() {
		while (true)
			r.take();
	}

}

public class Main {

	public static void main(String[] args) throws Exception {

		Scanner scanner = new Scanner(new BufferedInputStream(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		
		Resourse r = new Resourse();
		Producer a = new Producer(r);
		Producer b = new Producer(r);
		Consumer c = new Consumer(r);
		Consumer d = new Consumer(r);
		
		Thread t1 = new Thread(a);
		Thread t2 = new Thread(b);
		Thread t3 = new Thread(c);
		Thread t4 = new Thread(d);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}

  

以上是关于多线程的多消费者和多生产者signal和await的主要内容,如果未能解决你的问题,请参考以下文章

多线程-线程间通信-多生产者多消费者示例

多线程之Condition的await和signalsignalAll等待/通知机制

多线程生产者消费者模式中,如何停止消费者?多生产者情况下对“毒丸”策略的应用。

多线程_多生产者多消费者的实现问题

多线程应用——生产者消费者问题

Java——多线程高并发系列之Condition接口中的await()signal()signAll()方法