[英]More sophisticated way to terminate a thread ( Daemon thread or Thread.interrupt())
我编写了一个简单的程序来查找数字的阶乘。 我正在使用Thread
class 的join()
方法来更好地协调线程(并避免竞争条件)。 我在下面添加代码。
public static void main(String[] args) throws InterruptedException {
List<Long> listOfNumbers = new ArrayList<>(Arrays.asList(100031489L, 4309L, 0L, 199L, 333L, 23L));
List<FactorialCalculations> threadList = new ArrayList<>();
for (Long number : listOfNumbers) {
threadList.add(new FactorialCalculations(number));
}
for (Thread thread : threadList) {
thread.start();
}
for (Thread thread : threadList) {
thread.join(3000);
}
// Thread.sleep(1000);
for (int i = 0; i < listOfNumbers.size(); i++) {
FactorialCalculations factorialCalculationsThread = threadList.get(i);
if (factorialCalculationsThread.isStatus()) {
System.out.println("Factorial of number " + listOfNumbers.get(i) + " : " + factorialCalculationsThread.getResult());
} else {
System.out.println("still processing for " + listOfNumbers.get(i));
}
}
}
每当我输入一个大值 (100031489L)时,主线程都会打印除此之外的数字的输出,并且程序不会被终止。 我使用了两种方法 - 守护线程thread.setDaemon(true)
和thread.interrupt()
与Thread.currentThread().isInterrupted()
(如果 true 打印结果)来终止程序。 两种方法都有效,但我想知道在我的场景中使用哪种方法更合适。
提前致谢!
终止线程的常用方法是Thread.interrupt()
。 它可能更复杂,但会迫使您更好地理解工作流程,并让您知道将要执行哪些操作。
即使它在您的场景中可能并不重要,它可能会更好的一个原因是,如果您或其他人要在稍后退出的程序中重用您的代码并且您使用Thread.setDaemon()
,线程将不会终止直到程序退出,或者可能比您想要的更晚终止,而Thread.interrupt()
为您提供更多控制权。 您可能会在此问题中找到有关守护程序线程以及何时或为何应避免或使用它们的更好信息。
我对守护线程了解不多,我并不是说它们不好,但可能你应该知道何时使用它们以及可能存在哪些相关问题,我希望另一个问题对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.