Java线程: Is using interrupt() within run() acceptable to stop a thread when it is finished completing its task?

标签 java multithreading concurrency

我已经设置了一个 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/

相关文章:

java - 从 Java 中的泛型类型访问对象变量

java - 编写 customConsumerFactory 和 customKafkaListenerContainerFactory 时不会自动加载 spring kafka 属性

c++ - 如何从 C++/cx 中的嵌套任务返回值?

java - 在 Macbook Pro 上生成可听见的正弦波时出现 line.open() 错误

java - 如何调试 JAVA 堆内存不足错误

c - 快速解决死锁?

java - 将多个 Java 方法转换为非阻塞线程运行?

java - 仅尝试互联网连接几秒钟

java - OpenStack Swift 如何处理并发的 Restful API 请求?

java - volatile 读取和非 volatile 字段