java语言实现多生产者多消费者问题 多线程

package cn.itcast.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 * 多生产者,多消费者问题
 * 在JDK5.0中可以使用Lock类来建立锁
 * final Lock lock = new ReentrantLock();
 * final Condition pro_con = lock.newCondition();
 * final Condition con_con = lock.newCondition();
 * 
 * 
 */
public class ProducerAndConsumer {

	public static void main(String[] args) {

		BufferTest bt = new BufferTest();
		Producer p = new Producer(bt);
		Consumer c = new Consumer(bt);
		
		Thread t2 = new Thread(p);
		Thread t1 = new Thread(p);
		Thread t3 = new Thread(c);
		Thread t4 = new Thread(c);
		
		t1.setName("线程1");
		t2.setName("线程2");
		t3.setName("线程3");
		t4.setName("线程4");
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

class BufferTest {

	final Lock lock = new ReentrantLock();
	final Condition pro_con = lock.newCondition();
	final Condition con_con = lock.newCondition();

	final int[] b = new int[100];

	private int count = 0;
	private int takeptr = 0;
	private int putptr = 0;

	public void put() {

		try {
			lock.lock();
			while (count == b.length)
				pro_con.await();
			putptr++;
			if(putptr == b.length) putptr = 0;
			count++;
			System.out.println(Thread.currentThread().getName() + 
					"在" + putptr +"个位置,放入了一个数据,现在总共有" + count + "数据");
			con_con.signal();
			Thread.sleep(2000);
		} catch (InterruptedException e) {

			e.printStackTrace();

		} finally {
			lock.unlock();
		}

	}
	
	public void take(){
		
		try {
			lock.lock();
			while (count == 0)
				con_con.await();
			takeptr++;
			if(takeptr == b.length) takeptr = 0;
			count--;
			System.out.println(Thread.currentThread().getName() + 
					"在" + takeptr +"个位置,拿走了一个数据,现在总共有" + count + "数据");
			pro_con.signal();
			Thread.sleep(2000);
		} catch (InterruptedException e) {

			e.printStackTrace();

		} finally {
			lock.unlock();
		}
			
	}
}

class Producer implements Runnable{

	private BufferTest bt;
	
	public Producer(BufferTest bt) {
		this.bt = bt;
	}
	@Override
	public void run() {
		
		while(true){
			
			bt.put();
		}
		
	}
	
	
}


class Consumer implements Runnable{

	private BufferTest bt;
	
	public Consumer(BufferTest bt) {
		this.bt = bt;
	}
	@Override
	public void run() {
		
		while(true){
			
			bt.take();
		}
		
	}
	
	
}









你可能感兴趣的:(操作系统生产者与消费者)