考虑下面的代码:同步使用条件?我怎样才能使这个代码的性能和线程安全?
public class SomeClass {
private boolean shouldBlock = false;
private Object resource;
public void handleDrawRequest(Canvas canvas) {
if (!shouldBlock && resource == null)
{
shouldBlock = true;
loadTheResource(); //which takes awhile
shouldBlock = false;
}
else if (shouldBlock && resrouce == null)
{
return; //another thread is taking care of the loading of the resource
//and its not ready yet, so just ignore this request
}
drawResourceOn(canvas);
}
}
我怎样才能使此代码线程安全的?我试图完成的是只有一个线程来加载资源,同时任何其他线程试图同时访问此代码将被丢弃(例如,遵循'else if'逻辑)直到资源被加载。可能有很多线程试图同时访问这些代码,我不想同步整个方法并且有一堆线程堆积起来。
不确定你是否需要资源'volatile'。 – OldCurmudgeon 2012-02-12 01:51:02
看起来不错,简单。但是,加载资源可能会失败,将资源留空,我希望将来的线程能够重新加载资源。 AtomicReference可以帮助吗?或者就像在loadTheResource()之后添加loadingResource.compareAndSet(true,false)一样简单? –
2012-02-12 08:31:35
@Chris,如果加载资源失败,AtomicBoolean可以重置为false。 – Scorpion 2012-02-12 10:32:39