当要结束一个执行者的执行,您使用 shutdown() 方法告知它应该结束了。执行者等待正在允许或等待运行的任务的完成,然后结束执行。
如果您在 shutdown() 方法和执行者结束执行之间发给执行者一个任务,任务因为执行者不再接受新任务而被拒绝。 ThreadPoolExecutor 提供了一个机制,在一个任务被拒绝时调用。
本节的示例代码在 com.elanzone.books.noteeg.chpt4.sect12 package中
RejectedExecutionHandler 接口实现类: RejectedTaskController
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.printf("RejectedTaskController: The task %s has been rejected\n", r.toString()); System.out.printf("RejectedTaskController: %s\n", executor.toString()); System.out.printf("RejectedTaskController: Terminating: %s\n", executor.isTerminating()); System.out.printf("RejectedTaskController: Terminated: %s\n", executor.isTerminated()); }
线程类 : Task
private String name; public Task(String name) { this.name = name; }
@Override public void run() { System.out.println("Task " + name + ": Starting"); try { long duration = (long) (Math.random() * 10); System.out.printf("Task %s: ReportGenerator: Generating a report during %d seconds\n", name, duration); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Task %s: Ending\n", name); }
@Override public String toString() { return name; }
控制类 : Main
RejectedTaskController controller = new RejectedTaskController();
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); executor.setRejectedExecutionHandler(controller);
System.out.printf("Main: Starting.\n"); for (int i = 0; i < 3; i++) { Task task = new Task("Task" + i); executor.submit(task); }
System.out.printf("Main: Shutting down the Executor.\n"); executor.shutdown();
System.out.printf("Main: Sending another Task.\n"); Task task = new Task("RejectedTask"); executor.submit(task);