LockDemo 锁对象
class Resource {
private boolean flag = false;
private String name;
private int count;
//资源锁
Lock lock = new ReentrantLock();
//监视器类
Condition produce_con = lock.newCondition();
Condition customer_con = lock.newCondition();
public void set(String name){
//获取锁
lock.lock();
try{
while(flag)
//生产者线程等待
try{produce_con.await();}catch(Exception e){}
//直接唤醒消费者线程
customer_con.signal();
flag = true;
count++;
this.name = name;
System.out.println(this.name+" "+this.count);
}
finally{
//释放锁,不管try中代码是否报错,记得释放锁。
lock.unlock();
}
}
public void get(){
//获取锁
lock.lock();
try{
while(!flag)
//消费者线程等待
try{customer_con.await();}catch(Exception e){}
//直接唤醒生产者线程
produce_con.signal();
flag = false;
System.out.println(this.name+" customer"+this.count);
}
finally{
//释放锁资源
lock.unlock();
}
}
}
class Producer implements Runnable{
Resource s;
private Producer(){};
Producer(Resource t){
this.s = t;
}
public void run(){
int i = 0;
while(true){
if(i ==0)
s.set("rastduck");
else
s.set("car");
i = (i+1) %2;
}
}
}
class Customer implements Runnable{
Resource s;
private Customer(){}
Customer(Resource t){
this.s = t;
}
public void run(){
while(true){
s.get();
}
}
}
class LockDemo{
public static void main (String[] arg){
Resource s = new Resource();
Customer c = new Customer(s);
Producer p = new Producer(s);
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
Thread t3 = new Thread(p);
Thread t4 = new Thread(p);
t1.start();
t2.start();
t3.start();
t4.start();
}
}