【发布时间】:2025-11-29 04:25:01
【问题描述】:
我尝试在线程上设置超时,并期望执行程序抛出异常并阻止线程形式运行它终止它,但这不是超时工作发现的情况 但线程完成执行。 如果它通过超时,我如何终止线程? 这是我的测试代码:
class ArithmeticBB implements ArithmeticManagerCallable.ArithmeticAction {
@Override
public String arithmetic(String n) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String ss = n+" 2" + " ,Thread ID:" +Thread.currentThread().getId();
return ss;
}
}
public class ArithmeticManagerCallable {
ExecutorService executor = null;
private List<String> integerList = null;
private List<String> myResult= Collections.synchronizedList(new ArrayList<>());
private int threadTimeOutInSec = 180;
public ArithmeticManagerCallable(List<String> dataFromUser, int poolSize, int threadTimeOutInSec) {
this.integerList = dataFromUser;
executor = Executors.newFixedThreadPool(poolSize);
this.threadTimeOutInSec = threadTimeOutInSec;
}
private void exec(ArithmeticAction arithmeticAction) {
List<String> tempList = new ArrayList<>();
for(Iterator<String> iterator = integerList.listIterator(); iterator.hasNext();) {
tempList.add(arithmeticAction.arithmetic(iterator.next()));
}
resultArray.addAll(tempList);
}
public List<String> invokerActions(List<ArithmeticAction> actions) throws
InterruptedException {
Set<Callable<String>> callables = new HashSet<>();
for (final ArithmeticAction ac : actions) {
callables.add(new Callable<String>() {
public String call() throws Exception{
exec(ac);
return "done";
}
});
}
List<Future<String>> futures = executor.invokeAll(callables, this.threadTimeOutInSec, TimeUnit.SECONDS);
executor.shutdown();
while (!executor.isTerminated()) {
}
return myResult;
}
public interface ArithmeticAction {
String arithmetic(String n);
}
public static void main(String[] args) {
List<ArithmeticManagerCallable.ArithmeticAction> actions = new ArrayList();
actions.add(new ArithmeticBB());
List<String> intData = new ArrayList<>();
intData.add("1");
ArithmeticManagerCallable arithmeticManagerCallable = new ArithmeticManagerCallable(intData,20,4);
try {
List<String> result = arithmeticManagerCallable.invokerActions(actions);
System.out.println("***********************************************");
for(String i : result) {
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java multithreading timeout threadpool executorservice