给你个例子,14天视频里面有的
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Resource3{
private String name;
private int count = 1;
private boolean flag = false;
//创建一个锁对象。
Lock lock = new ReentrantLock();
//通过已有的锁获取该锁上的监视器对象。
// Condition c = lock.newCondition();
//通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者。
Condition producer_con = lock.newCondition();
Condition consumer_con = lock.newCondition();
public void set(String name){
lock.lock();
try{
while(flag)
try{producer_con.await();}
catch(InterruptedException e){}
this.name = name + count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者"+this.name);
flag = true;
consumer_con.signal();
}
finally{
lock.unlock();
}
}
public void get(){
lock.lock();
try{
while(!flag)
try{consumer_con.await();}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
producer_con.signal();
}
finally{
lock.unlock();
}
}
}
class Producer2 implements Runnable{
Resource3 r;
Producer2(Resource3 r){
this.r = r;
}
public void run(){
while(true){
r.set("烤鸭");
}
}
}
class Consumer2 implements Runnable{
Resource3 r;
Consumer2(Resource3 r){
this.r = r;
}
public void run(){
while(true){
r.get();
}
}
}
public class NewJDKDemo3 {
public static void main(String[] args) {
Resource3 r = new Resource3();
Producer2 pro = new Producer2(r);
Consumer2 con = new Consumer2(r);
Thread t0 = new Thread(pro);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(con);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
|