如何判斷開啓的多個線程都運行結束了?

package com.cdvcredit.vcar.job.scheduler;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@org.springframework.stereotype.Component
public class TaskTest {

    private Logger log = LoggerFactory.getLogger(getClass().getSimpleName());  

    private ExecutorService threadPool = Executors.newScheduledThreadPool(8);
    private CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);

    private AtomicInteger atomicInteger = new AtomicInteger();
    private Random random = new Random();

    @org.springframework.scheduling.annotation.Scheduled(cron = "0/3 * * * * ?")
    public void test(){
        long startTime = System.currentTimeMillis();
        int num = atomicInteger.getAndIncrement();
        log.info("任務開始 {} taskNum = {}", Thread.currentThread() , num);
        int length = 10;
        for(int i = 0 ;  i < length;  i++){
            TestCallable testCallable = new TestCallable(i);
            completionService.submit(testCallable);
        }
        log.debug("----測試中----");
        for(int i = 0 ;  i < length;  i++){
            try {
                int resultNum = completionService.take().get();
                log.debug("線程返回結果:{}", resultNum);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        long costTime = System.currentTimeMillis() - startTime;
        log.info("任務結束{} taskNum = {}, costTime = {}", Thread.currentThread(), num, costTime);
    }

    class TestCallable implements Callable<Integer>{

        private int i;

        TestCallable(int i){
            this.i = i;
        }

        @Override
        public Integer call() {
            int randomNumber = (random.nextInt(10)+1);
            try {
                log.debug("線程{}睡眠{}秒,i = {}",Thread.currentThread(),randomNumber, i);
                Thread.sleep(randomNumber*1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return i;
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章