私のアプリケーションの 1 つで、ExecutorService
クラスを使用して固定スレッド プールを作成CountDownLatch
し、スレッドが完了するのを待ちます。プロセスが例外をスローしなかった場合、これは正常に機能しています。いずれかのスレッドで例外が発生した場合は、実行中のすべてのスレッドを停止し、メイン スレッドにエラーを報告する必要があります。誰でもこれを解決するのを手伝ってもらえますか?
これは、複数のスレッドを実行するために使用しているサンプル コードです。
private void executeThreads()
{
int noOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
try
{
CountDownLatch latch = new CountDownLatch(noOfThreads);
for(int i=0; i< noOfThreads; i++){
executor.submit(new ThreadExecutor(latch));
}
latch.await();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
executor.shutDown();
}
}
これは実行者クラスです
public class ThreadExecutor implements Callable<String> {
CountDownLatch latch ;
public ThreadExecutor(CountDownLatch latch){
this.latch = latch;
}
@Override
public String call() throws Exception
{
doMyTask(); // process logic goes here!
this.latch.countDown();
return "Success";
}
================================================== ===========================
皆さん、ありがとうございました :)
以下のようにクラスを修正しましたが、現在は機能しています。
private void executeThreads()
{
int noOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
ArrayList<Future<Object>> futureList = new ArrayList<Future<Object>>(noOfThreads );
try
{
userContext = BSF.getMyContext();
CountDownLatch latch = new CountDownLatch(noOfComponentsToImport);
for(ImportContent artifact:artifactList){
futureList.add(executor.submit(new ThreadExecutor(latch)));
}
latch.await();
for(Future<Object> future : futureList)
{
try
{
future.get();
}
catch(ExecutionException e)
{ //handle it
}
}
}
catch (Exception e) {
//handle it
}
finally
{
executor.shutdown();
try
{
executor.awaitTermination(90000, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
//handle it
}
}
}
エグゼキュータ クラス:
public class ThreadExecutor implements Callable<String> {
private static volatile boolean isAnyError;
CountDownLatch latch ;
public ThreadExecutor(CountDownLatch latch){
this.latch = latch;
}
@Override
public String call() throws Exception
{
try{
if(!isAnyError)
{
doMyTask(); // process logic goes here!
}
}
catch(Exception e)
{
isAnyError = true ;
throw e;
}
finally
{
this.latch.countDown();
}
return "Success";
}