Java中线程池(Thread Pool)的使用

在多线程环境中使用Thread Pool,可以提高运行效率,以下是使用范例:

 

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class ThreadPoolManager
{
    private static Logger log = Logger.getLogger(ThreadPoolManager.class);

    private static ThreadPoolManager instance = new ThreadPoolManager();
    public static ThreadPoolManager getInstance()
    {
        return instance;
    }
   
    private static ThreadPoolExecutor taskPool = null; // Thread pool used to hold running threads
    private static BlockingQueue taskQueue = null; // Blocking queue used to hold waiting threads

    private static int corePoolSize;
    private static int maxPoolSize;
    private static int queueSize;
    private static long waitTime;

    private ThreadPoolManager()
    {
    }

    static
    {
        corePoolSize = Utility.THREAD_POOL_CORE_SIZE; // Config in properties, e.g. THREAD_POOL_CORE_SIZE=2
        queueSize = Utility.THREAD_POOL_QUEUE_SIZE; // Config in properties, e.g. THREAD_POOL_QUEUE_SIZE=2
        maxPoolSize = Utility.THREAD_POOL_MAX_SIZE; // Config in properties, e.g. THREAD_POOL_MAX_SIZE=4
        waitTime = Utility.THREAD_KEEP_ALIVE_TIME; // Config in properties, e.g. THREAD_KEEP_ALIVE_TIME=60
       
        taskQueue = new ArrayBlockingQueue(queueSize);
       
        taskPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, waitTime,
                TimeUnit.SECONDS, taskQueue, new ThreadPoolExecutor.CallerRunsPolicy());

        log.info("Initialize thread pool succeed. ThreadPool: corePoolSize = "
                + corePoolSize + ", queueSize = " + queueSize
                + ", maxPoolSize = " + maxPoolSize);
    }

    public void execute()
    {
        log.info("ThreadPoolManager.execute() - start");

        List lst = fetch();
        if (lst != null && lst.size() > 0)
        {
            log.info("ThreadPoolManager.execute() - List size is " + lst.size());
            int availTaskCount = 0;
            Long id = null;
            int index = 0;
            while (index < lst.size())
            {
                // If the amount of active threads and waiting threads does not reach the max thread limit,
                // create enough threads to either meet the max thread limit or meet the number of appIds to be deal with.
                availTaskCount = maxPoolSize - taskPool.getActiveCount() - taskQueue.size();
                log.debug("ThreadPool status - [active: " + taskPool.getActiveCount() + ", queue: " + taskQueue.size() + ", available: " + availTaskCount + "]");
                if (availTaskCount > 0)
                {
                    for (int i = index; i < index + availTaskCount && i < lst.size(); i++)
                    {
                        id = (Long)lst.get(i);
                        log.debug("ThreadPoolManager.execute()::Id: " + id);
                        taskPool.execute(Runnable command); // Some task extends Thread or implements Runnable interface
                    }
                    index = index + availTaskCount;
                }
                else
                {
                    log.debug("Sleep 500 ms while no enough threads available in thread pool");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        log.info("ThreadPoolManager.execute() - end");
    }
   
    private List fetch()
    {
        // dummy service method to fetch sth
        List lst = new ArrayList();
        return lst;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个Java创建线程池使用的示例代码: ``` import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo { public static void main(String[] args) { // 创建线程池,最多同时执行2个任务 ExecutorService threadPool = Executors.newFixedThreadPool(2); // 添加任务到线程池 for (int i = 1; i <= 5; i++) { final int index = i; threadPool.execute(new Runnable() { public void run() { System.out.println("任务 " + index + " 开始执行,线程名为 " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("任务 " + index + " 执行完毕,线程名为 " + Thread.currentThread().getName()); } }); } // 关闭线程池 threadPool.shutdown(); } } ``` 以上代码,我们使用`Executors.newFixedThreadPool()`方法创建一个固定大小的线程池,最多同时执行2个任务。然后使用`execute()`方法添加5个任务到线程池,每个任务都会打印出当前线程名,并让线程休眠1秒钟模拟任务执行的过程。最后使用`shutdown()`方法关闭线程池。 输出结果如下: ``` 任务 1 开始执行,线程名为 pool-1-thread-1 任务 2 开始执行,线程名为 pool-1-thread-2 任务 1 执行完毕,线程名为 pool-1-thread-1 任务 3 开始执行,线程名为 pool-1-thread-1 任务 2 执行完毕,线程名为 pool-1-thread-2 任务 4 开始执行,线程名为 pool-1-thread-2 任务 3 执行完毕,线程名为 pool-1-thread-1 任务 5 开始执行,线程名为 pool-1-thread-1 任务 4 执行完毕,线程名为 pool-1-thread-2 任务 5 执行完毕,线程名为 pool-1-thread-1 ``` 可以看到,线程池最多同时执行2个任务,任务执行的线程名不固定,任务执行完毕后,线程会自动回收。这样可以避免频繁的创建和销毁线程的开销,提高程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值