Thread.join()
將線程A加入到當(dāng)前執(zhí)行線程中,只有當(dāng)線程A執(zhí)行完畢,當(dāng)前線程才能繼續(xù)執(zhí)行;
join方法是同步的,使用synchronized關(guān)鍵字,底層調(diào)用wait方法;
例:
主線程在執(zhí)行過(guò)程中,調(diào)用線程對(duì)象threadA.join()方法,獲得了threadA對(duì)象的鎖,同時(shí)在join方法內(nèi)部調(diào)用threadA的wait方法阻塞當(dāng)前主線程;
Thread.ThreadLocal
InheritableThreadLocal,共享父類的ThreadLocal內(nèi)容;
https://zhuanlan.zhihu.com/p/28501035
Thread.interrupt()
如果當(dāng)前線程處于運(yùn)行狀態(tài),調(diào)用interrupt()只是設(shè)置當(dāng)前線程的中斷標(biāo)記位,不會(huì)中斷當(dāng)前線程的運(yùn)行;
如果當(dāng)前線程調(diào)用了wait或sleep方法,當(dāng)前線程處于阻塞狀態(tài),則線程清空中斷標(biāo)記位,并拋出InterruptedException異常;
Thread.interrupted(),判斷當(dāng)前線程是否處于中斷狀態(tài),如果是,返回true,同時(shí)清空中斷標(biāo)記位;即該方法第二次調(diào)用時(shí)將返回false;
Thread State
BLOCKED,線程阻塞在獲取鎖的時(shí)候
WAITING,線程調(diào)用了wait、join或LockSupport.park方法
Thread.stop() @Deprecated
調(diào)用stop方法,會(huì)釋放線程持有的所有鎖,此時(shí)原來(lái)被鎖保護(hù)的對(duì)象可能處于中間態(tài)。如果其他線程獲取了鎖,并對(duì)該中間態(tài)的對(duì)象進(jìn)行操作,結(jié)果無(wú)法確定;以下是官方注解。
Stopping a thread with * Thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequence of the unchecked * <code>ThreadDeath</code> exception propagating up the stack). If * any of the objects previously protected by these monitors were in * an inconsistent state, the damaged objects become visible to * other threads, potentially resulting in arbitrary behavior. Many * uses of <code>stop</code> should be replaced by code that simply * modifies some variable to indicate that the target thread should * stop running. The target thread should check this variable * regularly, and return from its run method in an orderly fashion * if the variable indicates that it is to stop running. If the * target thread waits for long periods (on a condition variable, * for example), the <code>interrupt</code> method should be used to * interrupt the wait.