增加對結果的處理:
1、修改Job,實現Callable接口
Java代碼
- public abstract class Job implements Callable<Object> {
- @Override
- public Object call() throws Exception {
- Object result = this.execute();//執行子類具體任務
- synchronized (Executer.LOCK) {
- //處理完業務后,任務結束,遞減線程數,同時喚醒主線程
- Executer.THREAD_COUNT--;
- Executer.LOCK.notifyAll();
- }
- return result;
- }
- /**
- * 業務處理函數
- */
- public abstract Object execute();
- }
2、修改Executer,增加對結果的處理
Java代碼
- public class Executer {
- //計算已經派發的任務數(條件謂詞)
- public static int THREAD_COUNT = 0;
- //存儲任務的執行結果
- private List<Future<Object>> futres = new ArrayList<Future<Object>>();
- //條件隊列鎖
- public static final Object LOCK = new Object();
- //線程池
- private ExecutorService pool = null;
- public Executer() {
- this(1);
- }
- public Executer(int threadPoolSize) {
- pool = Executors.newFixedThreadPool(threadPoolSize);
- }
- /**
- * 任務派發
- * @param job
- */
- public void fork(Job job){
- //將任務派發給線程池去執行
- futres.add(pool.submit(job));
- //增加線程數
- synchronized (LOCK) {
- THREAD_COUNT++;
- }
- }
- /**
- * 統計任務結果
- */
- public List<Object> join(){
- synchronized (LOCK) {
- while(THREAD_COUNT > 0){//檢查線程數,如果為0,則表示所有任務處理完成
- System.out.println("threadCount: "+THREAD_COUNT);
- try {
- LOCK.wait();//如果任務沒有全部完成,則掛起。等待完成的任務給予通知
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- List<Object> list = new ArrayList<Object>();
- //取出每個任務的處理結果,匯總后返回
- for (Future<Object> future : futres) {
- try {
- Object result = future.get();//因為任務都已經完成,這里直接get
- list.add(result);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return list;
- }
- }
3、測試:
Java代碼
- public static void main(String[] args) {
- //初始化任務池
- Executer exe = new Executer(5);
- //初始化任務
- long time = System.currentTimeMillis();
- for (int i = 0; i < 10; i++) {
- MyJob job = new MyJob();
- exe.fork(job);//派發任務
- }
- //匯總任務結果
- List<Object> list = exe.join();
- System.out.println("Result: "+list);
- System.out.println("time: "+(System.currentTimeMillis() - time));
- }
4、執行結果:
Java代碼
- threadCount: 10
- running thread id = 9
- running thread id = 11
- running thread id = 8
- running thread id = 10
- running thread id = 12
- threadCount: 5
- running thread id = 9
- running thread id = 8
- running thread id = 11
- running thread id = 12
- running thread id = 10
- Result: [8, 9, 10, 11, 12, 8, 11, 12, 9, 10]
- time: 2000
5、附件是完整代碼
- src.rar (2.2 KB)
- 下載次數: 11