【问题标题】:How to kill asynchronously running thread after timeout in java 8 and implications of doing thatjava 8超时后如何杀死异步运行的线程以及这样做的含义
【发布时间】:2020-02-13 11:18:04
【问题描述】:

我正在运行一个无限循环,需要实现以下步骤:

  1. 检查执行器服务中的可用线程(无限循环)
  2. 在循环中获取任务。
  3. 在后台执行任务(非阻塞),如果超过 3 秒,则终止执行任务的线程。

我已经研究了未来的 get API,它采用超时参数,但本质上不是阻塞。

while(any thread available in thread pool){

Task task = fetchTask();

// somehow execute this task in a non-blocking fashion with a timeout.


}

有没有办法在超时后杀死异步执行的线程? 超时后线程会停止执行并释放资源吗?

【问题讨论】:

  • 如果你使用线程池(执行器服务),你可能不想杀死线程而是取消任务。您可以通过使用带有超时的future.get() 来做到这一点 - 如果您需要异步等待,您可以从单独的线程或线程池中调用它。
  • Re,“……这样做的意义。”线程通过访问共享变量进行通信。如果您要杀死的线程必须临时将任何共享变量置于任何类型的不一致/无效/无意义的状态以完成其工作(即,如果有任何原因导致线程必须锁定锁),那么杀死线程可能会使这些变量处于不一致/无效/无意义的状态。此外,在一些编程系统(我忘记了Java)中,它也可能使锁永久锁定。

标签: java multithreading asynchronous java-8


【解决方案1】:

要实现这种行为,您需要这样做:

  1. 扩展 Thread 类并实现 可运行界面
  2. 一个线程执行器,用于简单地异步执行线程

让我们将其命名为“任务”的自定义类可以有一个特殊的实现,如下所示:

import java.util.Date;
import java.util.concurrent.Callable;

public class Task implements Callable<String> {

    private String name;
    private Long elapsedTimeInMillSeconds = 0L;
    static int counter = 0;

    public Task(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    @Override
    public String call() throws Exception {
        Long startTimeInNanoSeconds, endTimeInNanoSeconds;
        startTimeInNanoSeconds = System.nanoTime();
        System.out.println("Executing : " + name + ", Current Seconds : " + new Date().getSeconds());
        counter++;
        System.out.println("Counter = " + counter + " for thread number " + name);
        // Check if our logic is working as expected for Task2 we are going to delay for
        // 7 seconds
        if (counter == 2)
            Thread.sleep(7000);

        endTimeInNanoSeconds = System.nanoTime();
        elapsedTimeInMillSeconds = (endTimeInNanoSeconds - startTimeInNanoSeconds) / 10000;

        System.out
                .println("Thread [ name :  " + name + ", elapsed time  : " + this.elapsedTimeInMillSeconds + " Ms ] ");

        return "" + this.elapsedTimeInMillSeconds;
    }

    public synchronized Long getExecutionTime() {
        return elapsedTimeInMillSeconds;
    }

}

在你的主课上试试这个:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    static final int poolSize = 3;
    static int counter = 1;
    static final ExecutorService executor = Executors.newFixedThreadPool(poolSize);

    public static void main(String[] args) {
        List<Callable<Task>> callableTasks = new ArrayList<>();

        Callable t1 = new Task("Task1");
        Callable t2 = new Task("Task2");
        Callable t3 = new Task("Task3");
        callableTasks.add(t1);
        callableTasks.add(t2);
        callableTasks.add(t3);

        try {

            List<Future<Task>> futures = executor.invokeAll(callableTasks, 3, TimeUnit.SECONDS);
            futures.stream().forEach(Ft -> {

                Ft.cancel(true);
                Task task = null;
                try {
                    task = Ft.get();
                } catch (Exception e) {

                    throw new CancellationException("This Thread has been terminated ");

                }

            });
            executor.shutdownNow();
        } catch (Exception e) {

            if (e instanceof CancellationException) {
                System.out.println("Exception :  " + e.getMessage());

            }

        }
    }

}

计数器 == 2 的线程将被终止,这是我们延迟的原因

【讨论】:

  • 对不起,这不能回答问题
  • @stacky 能否请您在我上次更新后再次检查此代码
猜你喜欢
  • 1970-01-01
  • 2015-06-27
  • 1970-01-01
  • 2012-11-18
  • 2016-07-10
  • 1970-01-01
  • 2015-10-30
  • 2022-10-16
  • 1970-01-01
相关资源
最近更新 更多