1 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
這種方式具有競(jìng)爭(zhēng)條件:
public void getSomething(){
if(!isReady.get()){
new SampleThread().start();
}
//continue with the rest of the method
}
這是原子的: if(!isReady.get())但是與之關(guān)聯(lián)的條件語(yǔ)句的主體不是:
{
new SampleThread().start();
}
因此,您可以啟動(dòng)兩次該線程。
同步邏輯可防止出現(xiàn)競(jìng)爭(zhēng)情況。這也將增加對(duì)象上潛在的鎖定數(shù)量,但是if(!isReady.get())應(yīng)該快速執(zhí)行,這應(yīng)該是可以接受的。
請(qǐng)注意,AtomicBoolean如果布爾值僅在同步語(yǔ)句中使用,則可能不需要使用。
所以這里有兩種方式可以根據(jù)您的要求。
1)為了getSomething()開始第一次調(diào)用,SampleThread 并且其他線程在執(zhí)行之前等待初始化結(jié)束getSomething():
public void getSomething(){
synchronized(this){
// init the logic
if(!isReady){
SampleThread t = new SampleThread();
t.start();
t.join(); // wait for the SampleThread thread termination
isReady.set(true);
}
// execute the next only as the init thread was terminated
if(isReady){
//continue with the rest of the method
}
}
}
2)為了讓在第一次調(diào)用getSomething()開始SampleThread和別人線程不會(huì)等待此初始化執(zhí)行前結(jié)束getSomething():
public void getSomething(){
synchronized(this){
// init the logic once
if(!isReady.get()){
SampleThread t = new SampleThread();
t.start();
}
}
//continue with the rest of the method
}
并設(shè)置isReady以true在年底run()的SampleThread:
public void run(){
//Do some long running task once done
isReady.set(true);
}
添加回答
舉報(bào)