什么是线程池(Java)

1. 什么是线程池

线程池做的工作主要是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。

2. 特点作用

它的主要特点为线程复用控制最大并发数管理线程。

第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的销耗。

第二提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立即执行。

第三提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会销耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。

以下是一个简单的线程池和普通线程区别:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/***
 * @Author ljj
 */
public class ThreadVSPool {
    public static void main(String[] args) throws InterruptedException {
        thread();
        pool();
    }

    // 线程
    private static void thread() throws InterruptedException {
        Long start = System.currentTimeMillis();
        final Random random = new Random();
        final List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 100000; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    list.add(random.nextInt());

                }
            };
            thread.start();
            thread.join();
        }
        System.out.println("线程消耗");
        System.out.println("时间:" + (System.currentTimeMillis() - start));
        System.out.println("大小:" + list.size());
        System.out.println("------------------");
    }

    // 线程池
    private static void pool() throws InterruptedException {
        Long start = System.currentTimeMillis();
        final Random random = new Random();
        final List<Integer> list = new ArrayList<Integer>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 100000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    list.add(random.nextInt());
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
        System.out.println("线程池消耗");
        System.out.println("时间:"+(System.currentTimeMillis() - start));
        System.out.println("大小:"+list.size());
    }
}

运行结果:显然,使用线程池能让程序节省时间,提高响应速度

3. 线程池的使⽤

Java⾥⾯线程池的顶级接⼝是 java.util.concurrent.Executor ,但是严格意义上讲 Executor 并不是⼀个线程池,⽽只是⼀个执⾏线程的⼯具。真正的线程池接⼝是 java.util.concurrent. ExecutorService 。要配置⼀个线程池是⽐较复杂的,尤其是对于线程池的原理不是很清楚的情况 下,很有可能配置的线程池不是较优的,因此在 java.util.concurrent.Executors 线程⼯⼚类 ⾥⾯提供了⼀些静态⼯⼚,⽣成⼀些常⽤的线程池。官⽅建议使⽤ Executors ⼯程类来创建线程池对 象。

Java类库提供了许多静态⽅法来创建⼀个线程池:

Executors 类中创建线程池的⽅法如下:

a、newFixedThreadPool创建⼀个固定⻓度的线程池,当到达线程最⼤数量时,线程池的规模将不再变 化。

b、newCachedThreadPool创建⼀个可缓存的线程池,如果当前线程池的规模超出了处理需求,将回收 空的线程;当需求增加时,会增加线程数量;线程池规模⽆限制。

c、newSingleThreadPoolExecutor创建⼀个单线程的Executor,确保任务对了,串⾏执⾏。

d、newScheduledThreadPool创建⼀个固定⻓度的线程池,⽽且以延迟或者定时的⽅式来执⾏,类似 Timer;

1、Executors.newFixedThreadPool(int)

        newFixedThreadPool 创建的线程池corePoolSize和maximumPoolSize值是相等的,它使⽤ 的是LinkedBlockingQueue执⾏⻓期任务性能好,创建⼀个线程池,⼀池有N个固定的线程,有固定线程 数的线程。

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

2、Executors.newSingleThreadExecutor()

        newSingleThreadExecutor 创建的线程池corePoolSize和maximumPoolSize值都是1,它使 ⽤的是LinkedBlockingQueue⼀个任务⼀个任务的执⾏,⼀池⼀线程。

 public static ExecutorService newSingleThreadExecutor() {
     return new FinalizableDelegatedExecutorService
         (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
         new LinkedBlockingQueue<Runnable>()));
 }

3、Executors.newCachedThreadPool()

        newCachedThreadPool 创建的线程池将corePoolSize设置为0,将maximumPoolSize设置 为Integer.MAX_VALUE,它使⽤的是SynchronousQueue,也就是说来了任务就创建线程运⾏,当线程 空闲超过60秒,就销毁线程。

执⾏很多短期异步任务,线程池根据需要创建新线程,但在先前构建的线程可⽤时将重⽤它们。可扩 容,遇强则强。

public static ExecutorService newCachedThreadPool() {
     return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
         new SynchronousQueue<Runnable>());
 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值