目錄:
- 1仔戈、方法介紹:
- 1.1推姻、wait()、notify()
- 1.2课兄、join()方法
- 1.3牍氛、sleep()方法
- 2、實(shí)例demo:
- 2.1烟阐、wait()搬俊、notify()的demo
- 2.2、wait()蜒茄、notify() 原理時(shí)序圖
- 2.3唉擂、join()的demo
- 2.4、sleep()的demo
- 3檀葛、wait()玩祟、notify()的時(shí)序圖
- 4 、源碼分析:
- 4.1屿聋、wait()分析
- 4.2空扎、notify()分析
- 4.3、join()分析
- 5 润讥、總結(jié):
1转锈、方法介紹
1.1、wait()楚殿、notify()方法:
- 1黑忱、wait、notify以及notifyAll都是Object對(duì)象的方法勒魔,他們必須在被 synchronized 同步的方法或代碼塊中調(diào)用,否則會(huì)報(bào)錯(cuò)菇曲。
- 2冠绢、調(diào)用wait方法會(huì)使該線程進(jìn)入等待狀態(tài),并且會(huì)
釋放被同步對(duì)象的鎖
常潮。 - 3弟胀、notify操作可以喚醒一個(gè)因執(zhí)行wait而處于阻塞狀態(tài)的線程,使其進(jìn)入就緒狀態(tài)喊式,被喚醒的線程會(huì)去嘗試著獲取對(duì)象鎖孵户,然后執(zhí)行wait之后的代碼。如果發(fā)出notify操作時(shí)岔留,沒(méi)有線程處于阻塞狀態(tài)夏哭,那么該命令會(huì)忽略。
注意執(zhí)行notify并不會(huì)馬上釋放對(duì)象鎖献联,會(huì)等到執(zhí)行完該同步方法或同步代碼塊后才釋放
竖配。 - 4何址、notifyAll方法可以喚醒等待隊(duì)列中等待同一共享資源的“全部”線程從等待狀態(tài)--->就緒狀態(tài),進(jìn)行鎖爭(zhēng)奪进胯,類似第3天后面邏輯用爪。
1.2、join()方法:
- 1胁镐、jdk7中對(duì)join()定義:suspends the execution of the calling thread until the object called finishes its execution偎血。(暫停當(dāng)前正在執(zhí)行的線程,直到j(luò)oin的線程結(jié)束)
1.3盯漂、sleep()方法:
后補(bǔ)~
2颇玷、實(shí)例demo
2.1、wait()宠能、notify()的demo
/**
* @program: jvmproject
* @description: 線程的wait方法和notify方法
* @author: biudefu
* @create: 2019-07-28
**/
public class WaitAndNotifyMain {
static boolean flag = true;
static Object lock = new Object();
public static void main(String[] args) throws Exception {
Thread waitThread = new Thread(new Wait(), "WaitThread");
waitThread.start();
TimeUnit.SECONDS.sleep(1);
Thread notifyThread = new Thread(new Notify(), "NotifyThread");
notifyThread.start();
}
static class Wait implements Runnable {
public void run() {
// 加鎖亚隙,擁有l(wèi)ock的Monitor
synchronized (lock) {
// 當(dāng)條件不滿足時(shí),繼續(xù)wait违崇,同時(shí)釋放了lock的鎖
while (flag) {
try {
System.out.println(Thread.currentThread().getName() + " flag is true. wait @ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
lock.wait();
System.out.println(Thread.currentThread().getName() +" 被喚醒阿弃!@ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
} catch (InterruptedException e) {
}
}
// 條件滿足時(shí),完成工作
System.out.println(Thread.currentThread().getName() + " flag is false. running @ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
SleepUtils.second(5);
}
System.out.println(Thread.currentThread().getName() + " 結(jié)束?? @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
static class Notify implements Runnable {
public void run() {
// 加鎖羞延,擁有l(wèi)ock的Monitor
synchronized (lock) {
// 獲取lock的鎖渣淳,然后進(jìn)行通知,通知時(shí)不會(huì)釋放lock的鎖伴箩,
// 直到當(dāng)前線程釋放了lock后入愧,WaitThread才能從wait方法中返回
System.out.println(Thread.currentThread().getName() + " hold lock. notify @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
lock.notifyAll();
flag = false;
SleepUtils.second(4);
}
System.out.println(Thread.currentThread().getName() + " 釋放lock @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
SleepUtils.second(6);
// 再次加鎖
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " hold lock again. sleep @ "
+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
SleepUtils.second(5);
}
System.out.println(Thread.currentThread().getName() + " 結(jié)束?? @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
}
運(yùn)行結(jié)果:
2.2、wait()嗤谚、notify() 原理時(shí)序圖
2.3棺蛛、join()的demo
/**
* @program: jvmproject
* @description: 剖析Thread中的join方法
* @author: biudefu
* @create: 2019-08-28
**/
public class JoinMain {
public static void main(String[] args) throws Exception {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i++) {
// 每個(gè)線程擁有前一個(gè)線程的引用,需要等待前一個(gè)線程終止巩步,才能從等待中返回
Thread threadA = new Thread(new Domino(previous), String.valueOf(i));
threadA.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " terminate.");
}
static class Domino implements Runnable {
private Thread thread;
public Domino(Thread thread) {
this.thread = thread;
}
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + " terminate.");
}
}
}
運(yùn)行結(jié)果:
每個(gè)線程終止的前提是前驅(qū)線程終止旁赊,才會(huì)從join返回。
2.4椅野、sleep()的demo
后補(bǔ)
4 终畅、源碼分析
4.1、wait()¬ify()方法分析
4.2竟闪、join()方法分析
Thread.java中:
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) { //這個(gè)分支是無(wú)限期等待直到b線程結(jié)束离福。
while (isAlive()) {
wait(0); //wait操作,那必然有synchronized與之對(duì)應(yīng)炼蛤。--->synchronized void join(long millis)
}
} else { //這個(gè)分支是等待固定時(shí)間妖爷,如果b沒(méi)結(jié)束,那么就不等待了理朋。
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
Object.java中:
public final native void wait(long timeout) throws InterruptedException;
分析:
???????join()底層也是通過(guò)jdk的 native wait()來(lái)實(shí)現(xiàn)的赠涮。
注意這個(gè)wait()方法是Object類中的方法子寓,再來(lái)看sychronized鎖是哪個(gè)線程對(duì)象的?
public final synchronized void join(long millis) throws InterruptedException { ... }
??????? 成員方法加了synchronized說(shuō)明是synchronized(this)笋除,this是誰(shuí)靶庇选?this就是threadA線程對(duì)象本身
垃它。也就是說(shuō)鲜屏,主線程持有了threadA這個(gè)對(duì)象的鎖。
有了wait()国拇,必然有notify()洛史,什么時(shí)候才會(huì)notify呢?在jvm源碼里:
hotspot/src/share/vm/runtime/thread.cpp
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
......
// Notify waiters on thread object. This has to be done after exit() is called
// on the thread (if the thread is the last thread in a daemon ThreadGroup the
// group should have the destroyed bit set before waiters are notified).
ensure_join(this);
.......
}
static void ensure_join(JavaThread* thread) {
// We do not need to grap the Threads_lock, since we are operating on ourself.
Handle threadObj(thread, thread->threadObj());
assert(threadObj.not_null(), "java thread object must exist");
ObjectLocker lock(threadObj, thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
// Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
// Clear the native thread instance - this makes isAlive return false and allows the join()
// to complete once we've done the notify_all below
java_lang_Thread::set_thread(threadObj(), NULL);
// 此處看這一句
// thread就是當(dāng)前線程酱吝,是啥也殖?就是剛才例子中說(shuō)的threadA線程啊。
lock.notify_all(thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
}
線程threadA執(zhí)行完畢的時(shí)候务热,jvm會(huì)自動(dòng)喚醒阻塞在threadA對(duì)象上的線程忆嗜,在我們的demo中也就是主線程Main。至此崎岂,threadA線程對(duì)象被notifyall了捆毫,那么主線程也就能繼續(xù)跑下去了。
join()過(guò)程:join() 是一個(gè)synchronized方法冲甘, 底層調(diào)用了wait()绩卤,目的是讓持有這個(gè)同步鎖的線程進(jìn)入等待隊(duì)列,那么誰(shuí)持有了這個(gè)同步鎖呢江醇?答案是主線程濒憋,因?yàn)橹骶€程調(diào)用了threadA.join()方法,相當(dāng)于在threadA.join()代碼這塊寫(xiě)了一個(gè)同步代碼塊陶夜,誰(shuí)去執(zhí)行了這段代碼呢跋炕,是主線程,所以主線程被wait()了律适。然后在子線程threadA執(zhí)行完畢之后,JVM會(huì)調(diào)用lock.notify_all(thread);喚醒持有threadA這個(gè)對(duì)象鎖的線程遏插,也就是主線程捂贿,會(huì)繼續(xù)執(zhí)行。
4.3胳嘲、sleep()方法分析
后補(bǔ)~
總結(jié):
名稱 | join() | wait() | notify() | sleep() |
---|---|---|---|---|
底層實(shí)現(xiàn) | wait() | XXX | XXX | XXX |
鎖 | 釋放鎖 | 釋放鎖 | 不釋放 | 不釋放 |
參考資料:
《深入理解Java虛擬機(jī)-2nd》
《Java 并發(fā)編程實(shí)戰(zhàn)》
《Java 并發(fā)編程的藝術(shù)》