我有一個場景,我希望一個執行緒執行一些回圈操作,第二個(主)執行緒執行其他一些回圈作業,而第一個執行緒仍在執行其作業。
我的想法是使用CountDownLatch并等待它在主執行緒中完成:
public void process() {
CountDownLatch countDownLatch = new CountDownLatch(10_000);
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
for (int i = 0; i < 10_000; i ) {
// do some stuff
countDownLatch.countDown();
}
});
try {
while (!countDownLatch.await(5, SECONDS)) {
// do some other stuff...
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
問題是有時會在第一個(未來)執行緒中拋出例外,在這種情況下,繼續在主執行緒中執行代碼是沒有意義的。
我正在考慮將這種例外(從第一個執行緒拋出)的參考分配給 volatile 欄位,并在 main 的執行緒回圈中對這個欄位進行空檢查,看看它是否應該繼續回圈:
private volatile Exception innerException;
public void process() {
CountDownLatch countDownLatch = new CountDownLatch(10_000);
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
try {
for (int i = 0; i < 10_000; i ) {
// do some stuff
countDownLatch.countDown();
}
} catch (Exception e) {
this.innerException = e;
throw e;
}
});
try {
while (!countDownLatch.await(1, SECONDS)) {
// do some other stuff... but it doesn't make sense to continue
// if 'future' has thrown an exception, so let's rethrow it:
if (innerException != null) {
throw innerException;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error("Something bad happened in the 'future'! : ", e);
}
}
我想知道這是否是一個好(安全?)的想法,或者可能有一些更好的方法來解決這類問題?
感謝您對此的任何幫助,謝謝!
uj5u.com熱心網友回復:
您可以使用 future.get 在未來完成時進行同步。如果 Runnable/Callable 拋出例外,future.get 將拋出一個 ExecutionException。您可以完全擺脫 CountDownLatch。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373545.html
上一篇:從地圖中洗掉鍵集值時獲取UnSupportedOperationException
下一篇:MultiThread,ApartmentState.MTA點例外:System.PlatformNotSupportedException:此平臺不支持COMInterop
