我已经设置了一个Java
Thread
类,它执行一个特定的任务,创建一个新的Process
并与其他各种东西一起运行。Java线程:使用run()中的interrupt()是否可以在完成其任务时停止线程?
在其调用Thread
父类的我已经建立了循环
while(!thread.isActive()) {
...
}
我想知道这是否是最好的做法/接受更新run()
在Thread
类发出interrupt()
run() {
callTask();
interrupt();
}
更新
然后我可以在Thread
创建boolean
finished
场,并更改为true一旦callTask()完成,并有家长找
主题:
run() {
callTask();
finished = true;
}
家长:
// Start the threads for each Device
for (DeviceRunner deviceRunner : deviceRunners) {
deviceRunner.start();
}
boolean doneProcessingDevices = false;
while (!doneProcessingDevices) {
Set<DeviceRunner> deviceRunnersToRemove = new HashSet<DeviceRunner>();
for (DeviceRunner deviceRunner : deviceRunners) {
if (deviceRunner.isFinishedRunning()) { // check to see if the thread is finished
deviceRunnersToRemove.add(deviceRunner);
}
}
// remove the device runners which are no longer active
deviceRunners.removeAll(deviceRunnersToRemove);
if (deviceRunners.isEmpty()) {
doneProcessingDevices = true;
}
Thread.sleep(1000);
}
谢谢
你想让线程“中断”它对应的'Thread'对象,基本上会中断它自己吗? –
你想让一个线程自行中断吗?那是什么意思? 't.interrupt()'的目的是获得线程't'来关注一些已经改变的重要事情(通常是“关闭”请求)。你的线程不需要引起注意。它已经有了自己的关注。 –
@SotiriosDelimanolis我只是设置了中断,以便父线程知道线程何时完成。我注意到,即使线程在run()中不再有任何任务要执行,thread.isActive在某些情况下也会不断返回true。 我应该只是在线程中放入一个布尔值,然后更改它,并且在线程完成时让父级外观为它设置? – ALM