pool.execute(job);
//增加线程数
synchronized (LOCK) {
THREAD_COUNT++;
}
}
/**
* 统计任务结果
*/
public void join(){
synchronized (LOCK) {
while(THREAD_COUNT > 0){
System.out.println("threadCount: "+THREAD_COUNT);
try {
LOCK.wait();//如果任务没有全部完成,则挂起
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Java代码
public abstract class Job implements Runnable {
@Override
public void run() {
this.execute();//执行子类具体任务
synchronized (Executer.LOCK) {
//处理完业务后,任务结束,递减线程数,同时唤醒主线程
Executer.LOCK.notifyAll();
}
}
/**
* 业务处理函数
*/
public abstract void execute();
}
6、测试一下:
Java代码
threadCount: 10
running thread id = 8
running thread id = 11
running thread id = 9
threadCount: 7
running thread id = 10
threadCount: 6
running thread id = 12
threadCount: 5
running thread id = 11
running thread id = 12
running thread id = 10
threadCount: 2
running thread id = 9
running thread id = 8
threadCount: 1
time: 2016