天天看點

java 線程池之 newFixedThreadPool

  • 線程的實作方式
    • java 多線程之 extends Thread
    • java 多線程之 implements Runnable
    • java 多線程之 implements Callable
  • 線程池的使用
    • 線程池簡介
    • ThreadPoolExecutor
      • java 線程池之 newScheduledThreadPool
      • java 線程池之 newCachedThreadPool
      • java 線程池之 newFixedThreadPool
      • java 線程池之 newSingleThreadExecutor
    • ForkJoinPool
      • java 線程池之 newWorkStealingPool

java的線程池預設封裝了五個通用的線程池:

1、Executors.newSingleThreadExecutor()

2、Executors.newFixedThreadPool(2)

3、Executors.newCachedThreadPool()

4、Executors.newScheduledThreadPool(2)

5、Executors.newWorkStealingPool()

newFixedThreadPool的是執行個體化如下所示:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
           
java 線程池之 newFixedThreadPool

 和newSingleThreadExecutor唯一的差別就是核心線程池數和最大線程數可以按照需求自定義,其他的都是一緻的。

示例代碼:

public class FixedThreadPoolTest {
    // 線程數
    private static final int threads = 10;
    // 用于計數線程是否執行完成
    CountDownLatch countDownLatch = new CountDownLatch(threads);

    /**
     * newFixedThreadPool execute
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void test1() throws ExecutionException, InterruptedException {
        System.out.println("---- start ----");
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < threads; i++) {
            fixedThreadPool.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName());
                } catch (Exception e) {
                    System.out.println(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("---- end ----");
    }

    /**
     * newFixedThreadPool submit submit
     */
    @Test
    public void test2() throws InterruptedException {
        System.out.println("---- start ----");
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < threads; i++) {
//            Callable 帶傳回值
            fixedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            }));
        }
        countDownLatch.await();
        System.out.println("---- end ----");
    }

    /**
     * newFixedThreadPool submit Callable
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void test3() throws ExecutionException, InterruptedException {
        System.out.println("---- start ----");
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        for (int i = 0; i < threads; i++) {
//          Runnable 帶傳回值
            FutureTask<?> futureTask = new FutureTask<>(new Callable<String>() {
                /**
                 * call
                 * @return currentThreadName
                 */
                @Override
                public String call() {
                    return Thread.currentThread().getName();
                }
            });
            fixedThreadPool.submit(new Thread(futureTask));
            System.out.println(futureTask.get());
        }
        System.out.println("---- end ----");
    }
}