我有一些代码,在新线程上抛出异常,我需要在主线程上确认并处理它们。为了实现这一点,我正在使用一个字段来在线程之间共享状态,该字段保存抛出的异常。
我的问题是,当检查null时,我是否需要使用锁定,就像我在下面的代码示例中所做的那样?
```java synchronized (lock) { if (thrownException != null) { // handle exception on main thread } } ```
public class MyClass
{
readonly object _exceptionLock = new object();
Exception _exception;
public MyClass()
{
Task.Run(() =>
{
while (CheckIsExceptionNull())
{
// This conditional will return true if 'something has gone wrong'.
if(CheckIfMyCodeHasGoneWrong())
{
lock(_exceptionLock)
{
_exception = new GoneWrongException();
}
}
}
});
}
bool CheckIsExceptionNull() // Is this method actually necessary?
{
lock (_exceptionLock)
{
return _exception == null;
}
}
// This method gets fired periodically on the Main Thread.
void RethrowExceptionsOnMainThread()
{
if (!CheckIsExceptionNull())
{
lock (_exceptionLock)
{
throw _exception; // Does this throw need to be in a lock?
}
}
}
}
此外,在主线程上抛出异常时,我需要使用锁吗?