1 回答

TA貢獻1863條經驗 獲得超2個贊
這種方式具有競爭條件:
public void getSomething(){
if(!isReady.get()){
new SampleThread().start();
}
//continue with the rest of the method
}
這是原子的: if(!isReady.get())但是與之關聯的條件語句的主體不是:
{
new SampleThread().start();
}
因此,您可以啟動兩次該線程。
同步邏輯可防止出現競爭情況。這也將增加對象上潛在的鎖定數量,但是if(!isReady.get())應該快速執行,這應該是可以接受的。
請注意,AtomicBoolean如果布爾值僅在同步語句中使用,則可能不需要使用。
所以這里有兩種方式可以根據您的要求。
1)為了getSomething()開始第一次調用,SampleThread 并且其他線程在執行之前等待初始化結束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)為了讓在第一次調用getSomething()開始SampleThread和別人線程不會等待此初始化執行前結束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
}
并設置isReady以true在年底run()的SampleThread:
public void run(){
//Do some long running task once done
isReady.set(true);
}
添加回答
舉報