public void execute(Runnable command)
这个命令对象包含提交的对象,但它似乎被包裹了。
如何从自定义线程池执行器中访问提交的对象?或者尝试从 ThreadPoolExecutor 的之前/之后/执行方法内部访问提交的对象不是一个好主意吗?
最佳答案
不要使用execute
,使用submit
,它返回一个Future
,它是任务的句柄。下面是一些示例代码:
ExecutorService service = Executors.newCachedThreadPool();
Callable<String> task = new Callable<String>() {
public String call() throws Exception {
return "hello world";
}
};
Future<String> future = service.submit(task);
虽然您不能直接访问该任务,但您仍然可以与其进行交互:
future.cancel(); // Won't start task if not already started
String result = future.get(); // blocks until thread has finished calling task.call() and returns result
future.isDone(); // true if complete
您还可以与该服务进行交互:
service.shutdown(); //etc
编辑以纳入评论:
如果你想做一些日志记录,使用 anonymous class覆盖 afterExecute()
方法,如下所示:
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)) {
@Override
protected void afterExecute(Runnable r, Throwable t)
{
// Do some logging here
super.afterExecute(r, t);
}
};
根据需要覆盖其他方法。
快速插入:恕我直言,这个主题的圣经是Java Concurrency in Practice - 我建议您购买并阅读。
关于java - 从 ThreadPoolExecutor 中访问提交的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562742/