Java线程池ExecutorService 代码备忘

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5)
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
package UnitTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class test {
    public static void main(String[] args) {
        int flag = 0;
        long a = System.currentTimeMillis();
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        List<Future> resultList = new ArrayList<>();
        for (int i = 1; i < 101; i++) {
            Future future = fixedThreadPool.submit(new ThreadWithRunnable(i));
            resultList.add(future);
        }
        fixedThreadPool.shutdown();

        for (Future fs : resultList) {
            try {
                System.out.println(fs.get().toString());
                flag += Integer.parseInt(fs.get().toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.println(flag);
        System.out.println("\r<br>执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 ");

    }
}
package UnitTest;

import java.util.concurrent.Callable;

public class ThreadWithRunnable implements Callable {
    private int number;
    public ThreadWithRunnable(int number){
        this.number = number;
    }

    @Override
    public Object call() throws Exception {
        for (int i=1;i<1000;i++){
            Thread.sleep(1);
        }
        return number;
    }
}

 

posted @ 2019-02-15 13:54  缤纷世界  阅读(352)  评论(0编辑  收藏  举报