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

本文介绍了一种自定义调度器的设计与实现方案,通过使用Java的FutureTask和LinkedBlockingQueue来实现任务的异步调度与执行。该调度器能够有效处理任务执行过程中的异常,并确保线程的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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();
			}
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值