java:中断线程是绝对必要的

标签 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();
        }

现在是分派(dispatch)这些线程的部分代码:

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()

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

最佳答案

Oracle 在 javadocs 中提供的以下代码是大多数人所做的。据我所知,这是为了杀死那些在给它们关闭机会后拒绝正常关闭的线程。

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();
   }
 }

关于java:中断线程是绝对必要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10406581/

相关文章:

java - gradlew assemble 在 Travis-CI 上失败

java - 通知 Activity 类

c# - HttpClient.PostAsync ThreadPool 中没有足够的空闲线程来完成操作

java - wait 和 wait 的时差?

系统为后台音频应用程序提供的 iOS 通知

c - ATmega328 上 timer2 的奇怪行为

ruby - 区分命令行 Ruby 脚本信号的最佳方法

java - JAXB - 将相同的属性添加到不同的元素

java - 如何访问soap头信息?

multithreading - Spring AbstractRoutingDataSource背景线程