【发布时间】:2015-11-28 08:46:20
【问题描述】:
我在第 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 类,但其他类的结构相同,其中的代码几乎相同。现在程序结束,红色方块(终止按钮)仍然亮着,我读到这表明仍有线程在运行。我不知道为什么它没有停止。
【问题讨论】:
-
您的
th只是指向最后一只驯鹿。所以th.interrupt()只是打断那只驯鹿,没有其他线程。 -
您将需要存储对您稍后想要中断的所有线程的引用。
-
哦,我不知道。我认为
th指向所有线程,而不仅仅是前一个。谢谢! -
只为第一个圣诞节 var 名称投票。
标签: java multithreading interrupt