import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock2 {
public static void main(String[] args) {
ReSource rs=new ReSource();
Produce p=new Produce(rs);
Custom c=new Custom(rs);
Thread t=new Thread(p);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
Thread t3=new Thread(c);
t.start();
t1.start();
t2.start();
t3.start();
}
}
class ReSource
{
private int count=1;
private String name;
private boolean flag=false;
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
public void set(String name)
{
lock.lock();
try{
while(flag)
try {
notFull.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name=name+"..."+count++;
System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
flag=true;
notEmpty.signal();
}finally
{
lock.unlock();
}
}
public synchronized void get()
{
lock.lock();
try{
while(!flag)
try {
notEmpty.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"消费者"+this.name);
flag=false;
notFull.signal();
}finally
{
lock.unlock();
}
}
}
class Produce implements Runnable
{
private ReSource rs;
public Produce(ReSource rs)
{
this.rs=rs;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
rs.set("+商品+");
}
}
}
class Custom implements Runnable
{
private ReSource rs;
public Custom(ReSource rs)
{
this.rs=rs;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
rs.get();
}
}
} |