gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:36 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com