public class CustomScheduler implements Runnable {
private LinkedBlockingQueue activationQueue = new LinkedBlockingQueue();
@Override
public 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();
}
}
}
}
[JAVA学习笔记-97]ActiveObject模式的Scheduler的关键实现
最新推荐文章于 2022-12-22 12:48:13 发布