Quartz 1.5.2 线程池 SimpleThreadPool 简化分析

class SimpleThreadPool {

	private Object nextRunnableLock = new Object();

	private WorkThread[] works;

	private Runnable nextRunnable;

	private int count;

	public SimpleThreadPool(int count) {
		this.count = count;
		initialize();
	}

	public void initialize() {
		createWorkThread(count);
	}

	public void createWorkThread(int count) {
		works = new WorkThread[count];
		for (int i = 0; i < count; i++) {
			works[i] = new WorkThread();
			works[i].start();
		}
	}

	public void runInThread(Runnable runnable) {
		if (runnable == null)
			return;
		synchronized (nextRunnableLock) {
			while (nextRunnable != null) {
				try {
					nextRunnableLock.wait(1000);
				} catch (InterruptedException e) {
				}
			}

			nextRunnable = runnable;

			nextRunnableLock.notifyAll();

		}
	}

	public Runnable getNextRunnable() throws InterruptedException {
		Runnable toRun = null;
		synchronized (nextRunnableLock) {
			if (nextRunnable == null) {
				nextRunnableLock.wait(1000);
			}
			if (nextRunnable != null) {
				toRun = nextRunnable;
				nextRunnable = null;
				nextRunnableLock.notifyAll();
			}
		}
		return toRun;
	}

	class WorkThread extends Thread {
		private boolean run = true;
		
        void shutdown(){
        	run = false;
        }
		public void run() {
			while (run) {
				try {
					Runnable runnable = getNextRunnable();
					if (runnable != null) {
						runnable.run();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}
}

 

简化SimpleThreadPool 如上 SimpleThreadPool维护一个缓冲Runnable 变量nextRunnable, WorkThread 是工作线程类,初始化SimpleThreadPool的时候启动一定数量的工作线程,每个工作线程就是不停的通过getNextRunnable 方法去检查nextRunnable变量是否有值, 当然这里需要排队(同步)去拿,防止一个任务被多个线程执行,当他拿不到的时候就退对重新排队去拿。runInThread方法负责给工作线程分配任务,如果nextRunnable变量不为空,就等待,直到这个任务被工作线程取走,就在分配一个。

int seq = 1;
while (true) {
	try {
		System.out.println("Start assign job at " + new Date()
				+ " job name is job" + seq);
		tp.runInThread(new JobRunShell("job" + seq));
		seq++;
		Thread.sleep(1000);

	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 

 

Quartz 在系统初始化的时候只初始化一个QuartzSchedulerThread,QuartzSchedulerThread循环调用runInThread方法,当没有工作线程可用的时候 该方法阻塞。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值