当我收到通知时,我需要异步执行更新操作。下面的update()
方法操作实例变量。
public class UpdateOperation implements Runnable
{
private Boolean isInProgress = false;
@Override
public void run() {
try
{
synchronized (isInProgress)
{
isInProgress = true;
}
update(); //perform update
synchronized (isInProgress)
{
isInProgress = false;
}
}
catch (UpdaterException e)
{
// deal with it
}
}
}
// In another class
private UpdateOperation mCurrentUpdateOperation = new UpdateOperation();
public void updateRequired()
{
synchronized (mCurrentUpdateOperation.isInProgress)
{
if (!mCurrentUpdateOperation.isInProgress)
{
new Thread(mCurrentUpdateOperation).start();
}
else
{
// reschedule or silently ignore
}
}
}
此设置是否足以同时运行两 (2) 个更新操作?我相信这是因为第一个到达synchronized
块的线程将获取锁,启动操作,然后释放锁。然后第二个(或更多)将获取锁,查看操作正在进行中,重新调度并释放锁。
这个设置会失败吗?