java:绝对需要中断线程

时间:2012-05-02 01:31:12

标签: java multithreading interrupt

我是Java新手并使用某人提供的代码。在代码结束时,如果线程尚未完成,它们会中断一个线程。我正在测量代码的时间。

问题是Java代码首先发出所有线程,然后最终中断。中断是否必要?我们不能等到所有线程真正完成吗?或者可能只是跳过中断(这些线程正在使用process exec命令运行进程,无论如何它们都将完成)。 这是相关的代码。首先是单个线程的代码:

  String commandString = "./script.scr ";
  process = Runtime.getRuntime().exec(commandString);
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
  while ((lsString = bufferedReader.readLine()) != null)
        {
            System.out.println(lsString);
        }       
        try
        {
            process.waitFor();
        }

现在调度这些线程的部分的代码:

public void stopWhenAllTaskFinished()
{
    while(notFinished) {sleep(50);} //notFinished is class variable and somewhere else it will set to false. 
    //now finished.
  //Interrupt all the threads
    for (int i=0; i<nThreads; i++) {
        threads[i].interrupt();
    }
}

此函数从主类调用,如:

 obj.stopWhenAllTaskFinished()

我非常感谢任何见解或回答。

2 个答案:

答案 0 :(得分:2)

Oracle在javadocs中提供的以下代码是大多数人所做的。 AFAIK,用于杀死在给予机会关闭后拒绝正常关闭的线程。

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

答案 1 :(得分:1)

目前尚不清楚您发布的代码是否需要中断。

  • 如果在所有线程完成后notFinished设置为false,则不需要中断。

  • 如果某些线程可能尚未完成,notFinished设置为false,那么可能。是否真的有必要取决于其他事项:

    • 您是否已准备好让应用程序等待线程自然完成?
    • 你能确定线程完成吗? (他们可以永久地挂起/阻止吗?)
    • 你需要他们活动的结果吗?
    • 他们会回应中断吗? (在这种情况下,我认为答案是“是”。)
    • 将线留在那里有什么危害吗? (例如,它是否会停止应用程序关闭?)
相关问题