極客時(shí)間-《Java并發(fā)編程實(shí)戰(zhàn)》學(xué)習(xí)筆記
異步方法:調(diào)用方法,在方法中啟動(dòng)子線(xiàn)程
異步調(diào)用:?jiǎn)?dòng)子線(xiàn)程調(diào)用方法
異步轉(zhuǎn)同步:由于同步簡(jiǎn)單易用牵敷,將異步方法進(jìn)行封裝虽界,同步調(diào)用炫加,等待結(jié)果
Lock和Condition
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// method 加鎖
lock.lock();
try {
while(條件不滿(mǎn)足) {
condition.await(timeout);
}
// do something
......
} finally{
lock.unlock();
}
//method 釋放鎖
lock.lock()
try {
// do something
......
condition.signalAll();
} finally{
lock.unlock();
}
實(shí)現(xiàn)阻塞隊(duì)列
1個(gè)Lock窟哺、2個(gè)Condition(NotEmpty和NotFull)泻轰。入隊(duì)結(jié)束后NotEmpty發(fā)出信號(hào),出隊(duì)結(jié)束后NotEmpty發(fā)出信號(hào)且轨。
Dubbo同步轉(zhuǎn)異步
get(int timeout)方法和doReceived(Response res)方法浮声,可以看到使用Lock和Condition
Lock
Lock中有一個(gè)volatile標(biāo)示到state,在獲取鎖和釋放鎖都會(huì)對(duì)volatile變量讀寫(xiě)
根據(jù)happen-before特性
線(xiàn)程1-doSomething>線(xiàn)程1-unlock
線(xiàn)程1-unlock時(shí)會(huì)寫(xiě)state>線(xiàn)程2-lock時(shí)會(huì)讀state(volatile變量寫(xiě)先于讀)
線(xiàn)程1-doSomething>線(xiàn)程2-lock(根據(jù)前2個(gè)和happen-before傳遞性)
通過(guò)傳遞性和volatile變量寫(xiě)先于讀旋奢,保證加鎖后操作可見(jiàn)