1带兜、Object提供的等待通知方法
public class MainTest {
private static volatile int condition = 0;
private static final Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
while (condition != 1) {
try {
object.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("線程執(zhí)行完畢");
}
}
});
thread.start();
Thread.sleep(2000);
condition = 1;
synchronized (object) {
object.notify();
}
}
}
2汁尺、顯示鎖提供的等待通知
public class MainTest {
private static volatile int condition = 0;
private static ReentrantLock reentrantLock = new ReentrantLock();
private static Condition lockCondition = reentrantLock.newCondition();
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
try {
while (condition != 1) {
//lockCondition.wait();//不是下面這個(gè)玩意
//必須要獲取到鎖,不然報(bào)錯(cuò)徒河;
//和對(duì)象的wait()必須在同步塊中使用一個(gè)道理
lockCondition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
System.out.println("線程執(zhí)行完畢");
}
});
thread.start();
condition = 1;
reentrantLock.lock();
try {
Thread.sleep(2000);
lockCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
}
}
3系馆、區(qū)別
lock.newCondition() 獲取多個(gè)Condition對(duì)象。
在一個(gè)lock對(duì)象上顽照,可以有多個(gè)等待隊(duì)列由蘑。
而Object的等待通知只有一個(gè)等待隊(duì)列。
4代兵、源碼
Condition.await()會(huì)構(gòu)造一個(gè)新的等待隊(duì)列節(jié)點(diǎn)加入到等待隊(duì)列隊(duì)尾尼酿。
Condition.signal()會(huì)通知等待隊(duì)列隊(duì)首的節(jié)點(diǎn),將節(jié)點(diǎn)加入同步隊(duì)列植影。
見源碼