- wait() 阻塞秃流,釋放鎖
- notify() 通知阻塞的那個線程到就緒狀態(tài)糖赔,但不是讓出鎖給他刻撒,被喚醒的線程要運行必須得獲得鎖醋火。
示例:
public class NotifyFreeLock {
//添加volatile,使t2能夠得到通知
volatile List lists = new ArrayList();
public void add(Object o) {
lists.add(o);
}
public int size() {
return lists.size();
}
public static void main(String[] args) {
T04_NotifyFreeLock c = new T04_NotifyFreeLock();
final Object lock = new Object();
new Thread(() -> {
synchronized(lock) {
System.out.println("t2啟動");
if(c.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("t2 結(jié)束");
//通知t1繼續(xù)執(zhí)行
lock.notify();
}
}, "t2").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
new Thread(() -> {
System.out.println("t1啟動");
synchronized(lock) {
for(int i=0; i<10; i++) {
c.add(new Object());
System.out.println("add " + i);
if(c.size() == 5) {
lock.notify();
//釋放鎖为黎,讓t2得以執(zhí)行
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "t1").start();
}
}