我們之前寫代碼用對象來調(diào)用wait宅荤,notify,notifyAll,現(xiàn)在我們可以用Condition來定義一個等待喚醒機制贸呢,這樣就不用喚醒線程池里的所有線程,生產(chǎn)者喚醒消費者拢军,消費者喚醒生產(chǎn)者楞陷,大大提高了效率。等待時用await方法茉唉,喚醒時用signal方法固蛾。
import java.util.concurrent.locks.*;//導鎖包
class Resourse {
Object[] os = new Object[1];
Lock l = new ReentrantLock();
Condition Shengs = l.newCondition();// 定義生產(chǎn)者等待喚醒機制
Condition Xiaos = l.newCondition();// 定義消費者等待喚醒機制
int num = 1;
public void put(Object o) {
l.lock();
try {
if (os[0] != null) {
try {
Shengs.await();// 調(diào)用等待方法
} catch (Exception e) {
}
}
os[0] = o + "" + num;
num++;
System.out.println(Thread.currentThread().getName() + ".................." + os[0]);
Xiaos.signal();// 調(diào)用喚醒方法
} 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();
}
}