更复杂的终止线程的方法(Daemon线程或Thread.interrupt())。

问题描述 投票:0回答:1

我写了一个简单的程序来寻找数字的阶乘。我使用的是 join() 方式 Thread 类,以便更好地协调线程(并避免竞赛条件)。我正在添加下面的代码。

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() (如果为真,则打印结果) 来终止程序。这两种方法都有效,但我想知道在我的情况下,哪种方法更合适。

先谢谢你

java multithreading
1个回答
0
投票

通常终止一个线程的方法是 Thread.interrupt().它可能更复杂,但迫使你更好地理解工作流,让你知道要执行什么操作。

有一个原因可能会更好,即使它在你的方案中可能并不重要,那就是如果你或其他人要在以后退出的程序中重用你的代码,而你使用了 Thread.setDaemon()线程在程序退出前不会终止,也可能比你想要的时间晚终止,而 Thread.interrupt() 你可以找到关于守护进程线程的更好的信息,以及何时或为何应该避免或使用它们。这个问题.

我对守护神线程了解不多,我并不是说它们不好,但可能你应该知道什么时候使用它们,以及什么可能是一些相关的问题,我希望另一个问题能帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.