我已经设置了一个 Java
Thread
类,它执行创建新的 Process
并将其与各种其他事物一起运行的特定任务。
在调用Thread
的父类中,我设置了一个循环
while(!thread.isActive()) {
...
}
我想知道更新Thread
类中的run()
以发出interrupt()
是否是最佳实践/可接受的>
run() {
callTask();
interrupt();
}
更新
然后,我可以在 Thread
上创建一个 boolean
finished
字段,并在 callTask() 完成后将其更改为 true 并获得家长寻找
主题:
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);
}
谢谢
最佳答案
只是为了澄清:您不必手动停止线程。当 run()
完成时, native 线程将终止,并且 Thread
对象将被垃圾回收。
如果您希望 parent 等待所有任务完成,您可以使用 CountDownLatch
。使用必须完成的任务数初始化锁存器。每次任务完成时,让他调用 countDown()
。与此同时,你的父进程会阻塞 await()
:
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
此 MWE 演示了基本思想:
int numberOfTasks = 3;
CountDownLatch latch = new CountDownLatch(numberOfTasks);
while (numberOfTasks-- > 0) {
new Thread(() -> {
try {
// Do stuff.
System.out.println("Done.");
} finally {
latch.countDown();
}
}).start();
}
try {
latch.await();
System.out.println("All tasks finished.");
} catch (InterruptedException e) { /* NOP */ }
在每个任务打印 Done.
之前,您不会看到 Alltasksished.
。
关于Java线程: Is using interrupt() within run() acceptable to stop a thread when it is finished completing its task?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38748046/