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 打印输出永远不会出现。如果我使用第二种方法,我从运行程序开始就收到以下错误,并且 END MAIN 打印输出也永远不会出现:

出现异常:连接关闭后不允许进行任何操作。线程退出。

请以正确的方式告诉我,在我的所有子线程退出后让我的主线程退出。

4

1 回答 1

3

首先,为什么所有忙于旋转?最节省 CPU 的方法是只放一个非常 loooong awaitTermination

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

至于池未终止的原因,很可能是因为您的线程任务未正确终止。

于 2012-07-13T12:19:44.930 回答