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();
		}
		
	}
	
	
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值