即使在调用中断后,Java线程也不会停止

时间:2015-11-28 08:46:20

标签: java multithreading interrupt

我在第370天调用中断,然后在其他类的run方法期间在catch块期间再次调用它。我还有一个while循环条件,而线程没有被中断,但由于某种原因,它不起作用,我不知道为什么。我知道我可以使用变量标志,但我想尝试使interrupt()工作。我已经查看了多个网站,但似乎没有一个适合我。请帮忙。

public class Elf implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            // wait a day
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

public class Main {
    public static void main(String args[]) {
        Scenario scenario = new Scenario();
        // create the participants
        // Santa
        scenario.setSanta( new Santa(scenario) );
        Thread th = new Thread(scenario.getSanta());
        th.start();
        // The elves: in this case: 10
        for (int i = 0; i != 10; i++) {
            Elf elf = new Elf(i + 1, scenario);
            scenario.getElves().add(elf);
            th = new Thread(elf);
            th.start();
        }
        // The reindeer: in this case: 9
        for (int i = 0; i != 9; i++) {
            Reindeer reindeer = new Reindeer(i + 1, scenario);
            scenario.getReindeers().add(reindeer);
            th = new Thread(reindeer);
            th.start();
        }
        // now, start the passing of time
        for (int day = 1; day < 500; day++) {
            // wait a day
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            // turn on December
            if (day > (365 - 31)) {
                scenario.setDecember(true);
            }
            // interrupt flag is set here
            if (day == 370) {
                th.interrupt();
            }
            // print out the state:
            System.out.println("***********  Day " + day
                    + " *************************");
            scenario.getSanta().report();
            for (Elf elf : scenario.getElves()) {
                elf.report();
            }
            for (Reindeer reindeer : scenario.getReindeers()) {
                reindeer.report();
            }
        }
    }
}

我在这里只包含了Elf类,但其他类的结构相同,其中的代码几乎相同。现在程序结束时红色方块(终止按钮)仍然亮着,我读到这表明还有线程正在运行。我不确定为什么它没有停止。

1 个答案:

答案 0 :(得分:2)

声明为Thread th的变量是对Thread类型对象的引用。它只是对一个对象的引用。顺便说一下,对于所有类型,这不仅仅是线程。

每当您将新值放入变量时,它就不再引用旧值 [1]

因此,代码中的th.interrupt()将中断您分配给它的最后一个线程 - 最近的驯鹿线程。

如果要中断所有线程,则需要保留对所有线程的引用。

基本解决方案

执行此操作的一种简单方法是使用Thread列表:

List<Thread> allThreadsToInterrupt = new ArrayList<>();

创建线程时,执行

th = new Thread(...);
allThreadsToInterrupt.add(th);

然后最后你可以做到:

for ( Thread th: allThreadsToInterrupt ) {
    th.interrupt();
}

使用ThreadGroup

但事实上,Java有一个现有的类可以帮助你 - ThreadGroup类。你可以这样做:

ThreadGroup elfThreads = new ThreadGroup("Elf Threads");
ThreadGroup reindeerThreads = new ThreadGroup( "Reindeer Threads" );

现在,无论何时创建线程,都应该使用线程组创建它:

而不是:

th = new Thread(elf);

使用:

th = new Thread(elfThreads,elf);

然后在最后,为了打断所有精灵,你可以运行:

elfThreads.interrupt();

这会自动在所有属于该组的线程上调用interrupt()

当然,你可以创建一个大组,但我展示了将精灵和驯鹿分开,以防你需要它们被单独打断。

[1]在大多数情况下,使用新引用替换旧引用(这是对象的唯一引用)将导致旧对象有资格进行垃圾回收,但是线程有点不同,因为如果它们有已经启动,从当前线程组中有第二个引用它们(因为当你创建一个线程时没有给出一个线程组,这是默认值),这意味着它们不会是垃圾 - 收集,他们将正常运行,直到他们完成。