1 回答
![?](http://img1.sycdn.imooc.com/533e4cf4000151f602000200-100-100.jpg)
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);
}
添加回答
举报