java 并发框架中,使用ExecutorService运行任务,如果是Callable的任务 如何终止耗时比较久的任务(如网络连接),而且Callable任务好像没有Runnable可以查看状态
怎样为每个Callable任务设置超时,超时后停止任务
不像Runnable可以检测到中断信息,还是Callable也可以?
小伙看你根骨奇佳,潜力无限,来学PHP伐。
// Although it’s been a long time since I asked the question, I still wrote down the answer for everyone’s reference.
Possible ways to set a timeout for the Callable task are as follows:
Callable
I. Keep the Futureobject
Future
Future<Object> future = exec.submit(task);
II. Set the timeout period for waiting for the task to return results
int timeout = 5; future.get(timeout, TimeUnit.SECONDS);
III. Handling timeout exceptions
The complete sample code is as follows:
import java.util.concurrent.*; public class App { public static void main(String[] args) { ExecutorService exec = Executors.newSingleThreadExecutor(); Callable<Object> task = new Callable<Object>() { @Override public Object call() throws Exception { for (int i = 0; i < 10; i++) { // 任务需要运行10秒钟 TimeUnit.SECONDS.sleep(1); } return "task result."; } }; // 保留提交任务时所返回的`Future`对象 Future<Object> future = exec.submit(task); try { // 设置等待任务返回结果的超时时间 int timeout = 5; Object result = future.get(timeout, TimeUnit.SECONDS); System.out.println(result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { // 处理超时异常 System.err.println("超时了"); } exec.shutdown(); } }
// Although it’s been a long time since I asked the question, I still wrote down the answer for everyone’s reference.
Possible ways to set a timeout for the
Callable
task are as follows:I. Keep the
returned when submitting the taskFuture
objectII. Set the timeout period for waiting for the task to return results
III. Handling timeout exceptions
The complete sample code is as follows: