2

Java マルチスレッドを使用する次のコードがあります。

    ExecutorService threadExecutor = Executors.newFixedThreadPool(10);

    while(resultSet.next()) 
       { 
          name=resultSet.getString("hName");
          MyRunnable worker = new  Myrunnable(name);
          threadExecutor.execute( worker );
          Counter++;
    }


 threadExecutor.shutdown();
 System.out.println("thread shutdown");

 // Wait until all threads are finish
 while (! threadExecutor.isTerminated()) {

 }

 System.out.println("Finished all threads");

}// end try
    catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("END MAIN");

    DBConnection.con.close();           

そして、実行関数は次のとおりです。

//The constructor
MyRunnable (String name)  {
        this.name=name;
    }

public void run() 
{
        myclass Obj=new myclass();
        try {
            Obj.myFunction(name);
        } catch (Exception e) {

            System.out.println("Got an Exception: "+e.getMessage());
        }
        System.out.println(" thread exiting.");
}

以前の投稿で、スレッドが終了するまで待機する次のコードを誰かが提案しました。

while (! threadExecutor.isTerminated()) {
   try {
       threadExecutor.awaitTermination(1, TimeUnit.SECOND);
   }
   catch (InterruptedException e) {
        // you have to determine if someone can interrupt your wait
        // for the full termination of the executor, but most likely,
        // you'll do nothing here and swallow the exception, or rethrow
        // it in a RuntimeException
   }
}

今、私は両方のケースで問題に直面しています。最初の方法を使用した場合、プログラムは実行されますが、最後に、すべてのスレッドが終了する前に無限ループに入ります。END MAIN プリントアウトは表示されません。2 番目の方法を使用した場合、プログラムの実行の最初から次のエラーが発生し、END MAIN の出力も表示されません。

例外が発生しました: 接続が閉じられた後、操作は許可されません。スレッドの終了。

すべての子スレッドが終了した後にメインスレッドを終了させる正しい方法でアドバイスしてください。

4

1 に答える 1

3

まず最初に、なぜ忙しく回っているのか?最も CPU 効率の良い方法は、非常に loooong を置くことawaitTerminationです:

threadExecutor.shutdown();
threadExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

プールが終了しない原因については、スレッド タスクが適切に終了していないことが原因である可能性が最も高いです。

于 2012-07-13T12:19:44.930 に答える