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方法,当没有工作线程可用的时候 该方法阻塞。