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

多线程(多个生产者多个消费者 JDK5.0版本 Lock接口)

时间:2015-06-15 10:54:49      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:


/*
多线程:一个生产者一个消费者
*/
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

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