黑马程序员技术交流社区
标题:
昨天看多线程那个生产者消费者了,分享下。哈
[打印本页]
作者:
小悟空et
时间:
2015-5-29 10:53
标题:
昨天看多线程那个生产者消费者了,分享下。哈
真是,如果不天天练就手生,写这么短的程序,写了得半个小时,哎~~
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource
{
Lock lock = new ReentrantLock();
Condition proCon = lock.newCondition();
Condition conCon = lock.newCondition();
private String name;
private int count=1;
boolean flag = false;
public void set(String name) throws InterruptedException
{
lock.lock();
try{
while(flag)
proCon.await();
this.name = name +":"+ count++;
System.out.println(Thread.currentThread().getName()+"生产出了"+this.name);
flag = true;
conCon.signal();
}
finally
{
lock.unlock();
}
}
public void out() throws InterruptedException
{
lock.lock();
try
{
while(!flag)
conCon.await();
System.out.println(Thread.currentThread().getName()+"消费出了。。。。。。。"+this.name);
flag = false;
proCon.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch(InterruptedException e)
{
}
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch(InterruptedException e)
{
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2