gpt4 book ai didi

java - 如何在 Java 8 中超时后终止异步运行的线程以及这样做的含义

转载 作者:行者123 更新时间:2023-11-30 12:02:36 26 4
gpt4 key购买 nike

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

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

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

while(any thread available in thread pool){

Task task = fetchTask();

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


}

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

最佳答案

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

  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 的线程将被终止

关于java - 如何在 Java 8 中超时后终止异步运行的线程以及这样做的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com