标签:
/*
多线程:一个生产者一个消费者
*/
import java.util.concurrent.locks.*;
class Resource
{
	private String name;
	private int age;
	boolean flag=false;
	final Lock lock=new ReentrantLock();
	final Condition proCondition=lock.newCondition();
	final Condition selCondition=lock.newCondition();
	
	public void setResource(String name,int count)
	{
		lock.lock();
		try
		{
			while(flag)
				proCondition.await();
			this.name=name+count;
			System.out.println(Thread.currentThread().getName()+"生产者"+this.name+"......");
			flag=true;
			selCondition.signal();
		}
		catch(InterruptedException ex)
		{
			
		}
		finally
		{
			lock.unlock();
		}
	}
	public  String getName()
	{
		lock.lock();
		try
		{
			while(!flag)
				selCondition.await();
			flag=false;
			proCondition.signal();
			return this.name;
		}
		catch(InterruptedException ex)
		{
		
		}
		finally
		{
			lock.unlock();
		}
		return "";
	}
}
class ProducerThread implements Runnable
{
	int count=1;
	public Resource r=new Resource();
	public Resource getResource()
	{
		return r;
	}
	public void run()
	{
		while(true)
		{
			//try{r.setResource("张三",count);}catch(InterruptedException ex){}
			r.setResource("张三",count);
			count++;
		}
	}
}
class SellerThread implements Runnable
{
	private Resource r;
	int count=20;
	public SellerThread(Resource r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
			System.out.println(Thread.currentThread().getName()+"消费者"+r.getName()+"...");
			//try{System.out.println(Thread.currentThread().getName()+"消费者"+r.getName()+"...");}catch(InterruptedException ex){}
	}
}
class ManyProducerSellerThread2
{
	public static void main(String[] args) throws InterruptedException
	{
		ProducerThread pt=new ProducerThread();
		new Thread(pt).start();
		new Thread(pt).start();
		new Thread(new SellerThread(pt.getResource())).start();
		new Thread(new SellerThread(pt.getResource())).start();
	}
}
多线程(多个生产者多个消费者 JDK5.0版本 Lock接口)
标签:
原文地址:http://www.cnblogs.com/LenLi/p/4155841.html