我们之前写代码用对象来调用wait,notify,notifyAll,现在我们可以用Condition来定义一个等待唤醒机制,这样就不用唤醒线程池里的所有线程,生产者唤醒消费者,消费者唤醒生产者,大大提高了效率。等待时用await方法,唤醒时用signal方法。
import java.util.concurrent.locks.*;//导锁包
class Resourse {
Object[] os = new Object[1];
Lock l = new ReentrantLock();
Condition Shengs = l.newCondition();// 定义生产者等待唤醒机制
Condition Xiaos = l.newCondition();// 定义消费者等待唤醒机制
int num = 1;
public void put(Object o) {
l.lock();
try {
if (os[0] != null) {
try {
Shengs.await();// 调用等待方法
} catch (Exception e) {
}
}
os[0] = o + "" + num;
num++;
System.out.println(Thread.currentThread().getName() + ".................." + os[0]);
Xiaos.signal();// 调用唤醒方法
} finally {
l.unlock();
}
}
public void get() {
l.lock();
try {
if (os[0] == null) {
try {
Xiaos.await();
} catch (Exception e) {
}
}
System.out.println(Thread.currentThread().getName() + "==============" + os[0]);
os[0] = null;
Shengs.signal();
} finally {
l.unlock();
}
}
}
class Sheng implements Runnable {
private Resourse r;
Sheng(Resourse r) {
this.r = r;
}
public void run() {
while (true) {
r.put("啤酒");
}
}
}
class Xiao implements Runnable {
private Resourse r;
Xiao(Resourse r) {
this.r = r;
}
public void run() {
while (true) {
r.get();
}
}
}
class Demo1 {
public static void main(String[] args) {
Resourse r = new Resourse();
Sheng s = new Sheng(r);
Xiao x = new Xiao(r);
Thread ss = new Thread(s);
Thread ss2 = new Thread(s);
Thread ss3 = new Thread(x);
Thread ss4 = new Thread(x);
ss.start();
ss2.start();
ss3.start();
ss4.start();
}
}