import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import java.util.concurrent.locks.*;
/**
* Created by patkritLee on 2017/1/5.
*/
public class ProducerConsumerDemo {
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int cnt = 1;
private boolean flag = false;
private java.util.concurrent.locks.Lock lock = new ReentrantLock();
private Condition con_pro = lock.newCondition();
private Condition con_con = lock.newCondition();
public void set(String name) throws InterruptedException{
lock.lock();
try{
while(flag){
con_pro.await();
}
this.name = name+"--"+cnt++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag = true;
con_con.signal();
}
finally {
lock.unlock();
}
}
public void out() throws InterruptedException{
lock.lock();
try{
while(!flag){
con_con.await();
}
System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
flag = false;
con_pro.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){
}
}
}
}
部分运算结果:
Thread-0...生产者...+商品+--118676
Thread-3...消费者......+商品+--118676
Thread-0...生产者...+商品+--118677
Thread-2...消费者......+商品+--118677
Thread-0...生产者...+商品+--118678
Thread-3...消费者......+商品+--118678
Thread-0...生产者...+商品+--118679
Thread-2...消费者......+商品+--118679
Thread-0...生产者...+商品+--118680
Thread-3...消费者......+商品+--118680
Thread-0...生产者...+商品+--118681
Thread-2...消费者......+商品+--118681
Thread-0...生产者...+商品+--118682
Thread-3...消费者......+商品+--118682
Thread-0...生产者...+商品+--118683
Thread-2...消费者......+商品+--118683
Thread-0...生产者...+商品+--118684
Thread-3...消费者......+商品+--118684
Thread-0...生产者...+商品+--118685
Thread-2...消费者......+商品+--118685
Thread-0...生产者...+商品+--118686
Thread-3...消费者......+商品+--118686
Thread-0...生产者...+商品+--118687
Thread-2...消费者......+商品+--118687
Thread-0...生产者...+商品+--118688
Thread-3...消费者......+商品+--118688
Thread-0...生产者...+商品+--118689
Thread-2...消费者......+商品+--118689
Thread-0...生产者...+商品+--118690
Thread-3...消费者......+商品+--118690
Thread-0...生产者...+商品+--118691
Thread-2...消费者......+商品+--118691
Thread-1...生产者...+商品+--118692
Thread-3...消费者......+商品+--118692