线程池的创建及基本使用

线程池的创建及基本使用

使用ThreadPoolExecutor类创建线程池。


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

public class ThreadPoolTest {
        public static void main(String[] args){
            //创建等待队列
            BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
            //创建线程池,池中保存的线程数为3,允许的最大线程数为5
            ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,50, TimeUnit.MILLISECONDS,bqueue);
            //创建七个任务
            Runnable t1 = new MyThread();
            Runnable t2 = new MyThread();
            Runnable t3 = new MyThread();
            Runnable t4 = new MyThread();
            Runnable t5 = new MyThread();
            Runnable t6 = new MyThread();
            Runnable t7 = new MyThread();
            //每个任务会在一个线程上执行
            pool.execute(t1);
            pool.execute(t2);
            pool.execute(t3);
            pool.execute(t4);
            pool.execute(t5);
            pool.execute(t6);
            pool.execute(t7);
            //关闭线程池
            pool.shutdown();
        }
    }

    class MyThread implements Runnable{
        @Override
        public void run(){
            System.out.println(Thread.currentThread().getName() + "正在执行……");
            try{
                Thread.sleep(100);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }

运行的结果是:

pool-1-thread-3正在执行……
pool-1-thread-1正在执行……
pool-1-thread-2正在执行……
pool-1-thread-2正在执行……
pool-1-thread-3正在执行……
pool-1-thread-1正在执行……
pool-1-thread-2正在执行……

我们共创建了7个任务,然后创建了3个线程先执行;

我们在来学习一个其够着方法,看创建一个线程池我们需要传人的参数:

public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long  keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue)

• corePoolSize:线程池中所保存的核心线程数,包括空闲线程。
• maximumPoolSize:池中允许的最大线程数。
• keepAliveTime:线程池中的空闲线程所能持续的最长时间,当线程池中的线程数量小于 corePoolSize 时,如果里面有线程的空闲时间超过了 keepAliveTime,就将其移除线程池,这样,可以动态地调整线程池中线程的数量。
• unit:持续时间的单位。
• workQueue:任务执行前保存任务的队列,仅保存由 execute 方法提交的 Runnable 任务。

在整个任务提交到线程池执行的过程是:

  1. 如果线程池中的线程数量少于 corePoolSize,即使线程池中有空闲线程,也会创建一个新的线程来执行新添加的任务;
  2. 如果线程池中的线程数量大于等于 corePoolSize,但缓冲队列 workQueue 未满,则将新添加的任务放到 workQueue 中,按照 FIFO 的原则依次等待执行(线程池中有线程空闲出来后依次将缓冲队列中的任务交付给空闲的线程执行);
  3. 如果线程池中的线程数量大于等于 corePoolSize,且缓冲队列 workQueue 已满,但线程池中的线程数量小于 maximumPoolSize,则会创建新的线程来处理被添加的任务;
  4. 如果线程池中的线程数量等于了 maximumPoolSize,有 4 种才处理方式(该构造方法调用了含有 5 个参数的构造方法,并将最后一个构造方法为 RejectedExecutionHandler 类型,它在处理线程溢出时有 4 种方式,这里不再细说,要了解的,自己可以阅读下源码)。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值