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的關鍵實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.