package com.lsh.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ProducerConsumerDemo2
{
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 count=0;
private boolean tag=false;
Lock lock=new ReentrantLock();
Condition con=lock.newCondition();
public synchronized void set(String name) throws InterruptedException{
lock.lock();
try{
while(tag){
con.await();
}
this.name=name+"-------"+count++;
System.out.println(Thread.currentThread().getName()+"--生产者--"+this.name);
tag=true;
con.signalAll();
}finally{
lock.unlock();
}
}
public synchronized void get() throws InterruptedException{
lock.lock();
try{
while(!tag){
con.await();
}
System.out.println(Thread.currentThread().getName()+"--+消费者+--"+this.name);
tag=false;
con.signalAll();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable
{
private Resource r=new Resource();
Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
try {
r.set("商品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable
{
private Resource r=new Resource();
Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
try {
r.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |