[JAVA学习笔记-97]ActiveObject模式的Scheduler的关键实现

来源:互联网 发布:广联达破解软件下载 编辑:程序博客网 时间:2024/06/05 06:15

public class CustomScheduler implements Runnable {private LinkedBlockingQueue activationQueue = new LinkedBlockingQueue();@Overridepublic void run() {dispatch();}public Future enqueue(Callable methodRequest) {final FutureTask task = new FutureTask(methodRequest) {public void run() {try {super.run(); 【调用FutureTask的run,实际调用的是callable的run】// 捕获所有可能抛出的对象,避免该任务运行失败而导致其所在的线程终止} catch (Throwable t) {this.setException(t);}}};try {activationQueue.put(task);} catch (InterruptedException e) {Thread.currentThread().interrupt();}return task;}public void dispatch() {while (true) {Runnable methodRequest;try {methodRequest = activationQueue.take();// 防止个别任务执行失败导致线程终止的代码在run方法中methodRequest.run();} catch (InterruptedException e) {// 处理该异常e.printStackTrace();}}}}





阅读全文
0 0