java线程池之newFixedThreadPool

Posted 胡乐天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程池之newFixedThreadPool相关的知识,希望对你有一定的参考价值。

newFixedThreadPool 测试类

package com.thread.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestFixedThreadPool {

    public static void main(String[] args) {
        /**
         *  调用方法 new ThreadPoolExecutor(nThreads, nThreads,
         *                                       0L, TimeUnit.MILLISECONDS,
         *                                       new LinkedBlockingQueue<Runnable>());
         * newFixedThreadPool:用来创建一个固定大小的线程池
         * 只有一个参数,nThreads,即核心线程数和最大线程数
         * 采用无界的阻塞队列,可以存储最大整数个任务,所以实际的线程数量永远不会变化
         * 对当前线程数量进行限制,保证线程数可控,不会造成线程更多,导致系统负载更为严重。
         * 适用于负载较重的场景
         */
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        for (int i=0;i<500;i++){
            ThreadPool threadPool = new ThreadPool(""+i);
            executorService.execute(threadPool);

        }
        executorService.shutdown();
    }
}

线程任务类

package com.thread.pool;

import java.util.Date;

public class ThreadPool implements Runnable {

    private static ThreadPool threadPool = null;
    String name;

    public ThreadPool(String name){
        this.name = name;
    }
    @Override
    public void run() {
        doSomeThing();
    }

    public static synchronized Runnable getInstance(){
        if(threadPool == null){
            threadPool = new ThreadPool("getInstance");
        }
        return getInstance();
    }

    private void doSomeThing() {

        for (int i=0;i<10;i++){
            System.out.println((new Date()).toLocaleString() + "   " + Thread.currentThread().getName() + "执行" +i + ",name=" + name);
        }

       /* try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}

以上是关于java线程池之newFixedThreadPool的主要内容,如果未能解决你的问题,请参考以下文章

java线程池之ThreadPoolExecutor

java线程池之newSingleThreadExecutor

Java线程池之ForkJoinPool

java线程池之newCachedThreadPool

java线程池之newFixedThreadPool

Java 线程池之FixedThreadPool(Java代码实战-003)