码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-11-03 20:19:42      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:ref   this   buffer   scale   ade   package   runnable   boolean   class   

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

标签:ref   this   buffer   scale   ade   package   runnable   boolean   class   

原文地址:https://www.cnblogs.com/WINDZLY/p/11788632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!