2

を使用してスレッドのプールを作成しますが、Executors.newFixedThreadPoolしばらくすると、一部のスレッドが応答を停止したことに気付きました (以下でこのメソッドを呼び出します)。

彼らは破壊されましたか?私は同期を行っており、タスクを終了したすべてのスレッドが設定されるとシステムは続行しますが、これでシステムはデッドロックに陥ります。

彼らは破壊されましたか?これを防止または処理するにはどうすればよいですか?

//this is the method that threads call when finish the work
synchronized void setTaskFinish(){
    System.out.println(Thread.currentThread().getName() + " finishing the work.");        
    finishedThreads++;  
    System.out.println(finishedThreads +" finished the work.");
    if(finishedThreads == numberThreads){            
        finishedThreads = 0;
        this.notify();
    }
}

//this is the method that creates the thread
//I dont know much about this executors yet, so I think it have errors
public void execute(int numberThreads) {    
    for (int i = 0; i < numberThreads; i++) {
        crawlers.add(new SlaveCrawler());
    }

    ExecutorService threadExecutor = Executors.newFixedThreadPool(numberThreads);        

    for (int i = 0, n = crawlers.size(); i < n; i++) {
        threadExecutor.execute((Runnable) crawlers.get(i));
    }      

    threadExecutor.shutdown();        
}

編集:私は自分の論理を完全に変更しました。私は多くのテストを行っていませんが、今はすべて問題ないようです。私の古い論理では何かが間違っていたのかもしれません。

4

1 に答える 1

1

エグゼキューターは、タスクの実行でビジー状態のスレッドを破棄しません。60 個のタスクを割り当てて、「完了」したタスクが 55 個しかない場合 (より正確には、setTaskFinish()メソッドが 55 回しか呼び出されない場合)、例外としてタスクが途中で終了する可能性があります。デッドロックも別の可能性ですが、最初に検討することはありません。

タスクが次のような未チェックの例外をスローするとどうなりますRuntimeExceptionか? ブロックsetTaskFinish()から呼び出しますか?finallyなぜsynchronized代わりにを使用して同時実行を管理しているのAtomicIntegerですか?

于 2011-05-18T20:05:03.733 に答える