使用一个 executor,您不必管理线程。只需要实现 Runnable 或 Callable 任务并发给 executor。 executor负责创建线程、在线程池中管理、如果不再需要则结束它们。 有时您想取消一个已送去 executor 的任务。此时可使用 Future 的 cancel() 方法来执行取消操作。
本节的示例代码在 com.elanzone.books.noteeg.chpt4.sect09 package中
Callable<String> 类: Task
public class Task implements Callable<String> { @Override public String call() throws Exception { while (true){ System.out.printf("Task: Test\n"); Thread.sleep(100); } } }
控制类 : Main
ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors.newCachedThreadPool();
Task task = new Task(); System.out.printf("Main: Executing the Task\n"); Future<String> result = executor.submit(task);
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.printf("Main: Canceling the Task\n"); result.cancel(true);
System.out.printf("Main: Canceled: %s\n", result.isCancelled()); System.out.printf("Main: Done: %s\n",result.isDone());
executor.shutdown(); System.out.printf("Main: The executor has finished\n");