Java线程池

ThreadPoolExecutor

线程池类为java.util.concurrent.ThreadPoolExecutor,常用构造方法为:

 

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,

                                       BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)

  • corePoolSize: 线程池维护线程的最少数量
  • maximumPoolSize:线程池维护线程的最大数量
  • keepAliveTime: 线程池维护线程所允许的空闲时间
  • unit: 线程池维护线程所允许的空闲时间的单位
  • workQueue: 线程池所使用的缓冲队列
  • handler: 线程池对拒绝任务的处理策略
 
一个任务通过execute(Runnable)方法被添加到线程池,任务就是一个Runnable类型的对象,任务的执行方法就是Runnable类型对象的run()方法。
 
当一个任务通过execute(Runnable)方法欲添加到线程池时:
  1. 如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
  2. 如果此时线程池中的数量等于corePoolSize,但是缓冲队列workQueue未满,那么任务被放入缓冲队列。
  3. 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
  4. 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
  5. 当线程池中的线程数量大于corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
 
unit可选的参数为java.util.concurrent.TimeUnit中的几个静态属性:
  1. NANOSECONDS
  2. MICROSECONDS
  3. MILLISECONDS
  4. SECONDS
 
workQueue常用的是:java.util.concurrent.ArrayBlockingQueue
 
handler有四个选择:
  1. ThreadPoolExecutor.AbortPolicy(),抛出java.util.concurrent.RejectedExecutionException异常
  2. ThreadPoolExecutor.CallerRunsPolicy(),重试添加当前的任务,他会自动重复调用execute()方法
  3. ThreadPoolExecutor.DiscardOldestPolicy(),抛弃旧的任务
  4. ThreadPoolExecutor.DiscardPolicy(),抛弃当前的任务


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

public class TestThreadPool
{
    private static int produceTaskMaxNumber = 100;

    public static void main(String[] args)
    {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, 32, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        for (int i = 1; i <= produceTaskMaxNumber; i++)
        {
            try
            {
                String task = "task@ " + i;
                System.out.println("创建任务并提交到线程池中:" + task);
                threadPool.execute(new ThreadPoolTask(task));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        
        threadPool.shutdown();
    }
}

class ThreadPoolTask implements Runnable
{
    private Object attachData;

    ThreadPoolTask(Object tasks)
    {
        this.attachData = tasks;
    }

    public void run()
    {
        System.out.println("开始执行任务:" + attachData);
        System.out.println(Thread.currentThread().getName());
        attachData = null;
        
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

运行结果:

创建任务并提交到线程池中:task@ 1
创建任务并提交到线程池中:task@ 2
开始执行任务:task@ 1
pool-1-thread-1
创建任务并提交到线程池中:task@ 3
开始执行任务:task@ 2
pool-1-thread-2
创建任务并提交到线程池中:task@ 4
开始执行任务:task@ 3
pool-1-thread-3
创建任务并提交到线程池中:task@ 5
创建任务并提交到线程池中:task@ 6
创建任务并提交到线程池中:task@ 7
创建任务并提交到线程池中:task@ 8
开始执行任务:task@ 4
pool-1-thread-4
创建任务并提交到线程池中:task@ 9
开始执行任务:task@ 8
pool-1-thread-5
创建任务并提交到线程池中:task@ 10
开始执行任务:task@ 9
pool-1-thread-6
创建任务并提交到线程池中:task@ 11
开始执行任务:task@ 10
pool-1-thread-7
创建任务并提交到线程池中:task@ 12
开始执行任务:task@ 11
pool-1-thread-8
创建任务并提交到线程池中:task@ 13
开始执行任务:task@ 12
pool-1-thread-9
创建任务并提交到线程池中:task@ 14
开始执行任务:task@ 13
pool-1-thread-10
创建任务并提交到线程池中:task@ 15
开始执行任务:task@ 14
pool-1-thread-11
创建任务并提交到线程池中:task@ 16
开始执行任务:task@ 15
pool-1-thread-12
创建任务并提交到线程池中:task@ 17
开始执行任务:task@ 16
pool-1-thread-13
创建任务并提交到线程池中:task@ 18
开始执行任务:task@ 17
pool-1-thread-14
创建任务并提交到线程池中:task@ 19
开始执行任务:task@ 18
pool-1-thread-15
创建任务并提交到线程池中:task@ 20
开始执行任务:task@ 19
pool-1-thread-16
创建任务并提交到线程池中:task@ 21
开始执行任务:task@ 20
pool-1-thread-17
创建任务并提交到线程池中:task@ 22
开始执行任务:task@ 21
pool-1-thread-18
创建任务并提交到线程池中:task@ 23
开始执行任务:task@ 22
pool-1-thread-19
创建任务并提交到线程池中:task@ 24
开始执行任务:task@ 23
pool-1-thread-20
创建任务并提交到线程池中:task@ 25
开始执行任务:task@ 24
pool-1-thread-21
创建任务并提交到线程池中:task@ 26
开始执行任务:task@ 25
pool-1-thread-22
创建任务并提交到线程池中:task@ 27
开始执行任务:task@ 26
pool-1-thread-23
创建任务并提交到线程池中:task@ 28
开始执行任务:task@ 27
pool-1-thread-24
创建任务并提交到线程池中:task@ 29
开始执行任务:task@ 28
pool-1-thread-25
创建任务并提交到线程池中:task@ 30
开始执行任务:task@ 29
pool-1-thread-26
创建任务并提交到线程池中:task@ 31
开始执行任务:task@ 30
pool-1-thread-27
创建任务并提交到线程池中:task@ 32
开始执行任务:task@ 31
pool-1-thread-28
创建任务并提交到线程池中:task@ 33
开始执行任务:task@ 32
pool-1-thread-29
创建任务并提交到线程池中:task@ 34
开始执行任务:task@ 33
pool-1-thread-30
创建任务并提交到线程池中:task@ 35
开始执行任务:task@ 34
pool-1-thread-31
创建任务并提交到线程池中:task@ 36
创建任务并提交到线程池中:task@ 37
创建任务并提交到线程池中:task@ 38
创建任务并提交到线程池中:task@ 39
创建任务并提交到线程池中:task@ 40
创建任务并提交到线程池中:task@ 41
创建任务并提交到线程池中:task@ 42
创建任务并提交到线程池中:task@ 43
创建任务并提交到线程池中:task@ 44
创建任务并提交到线程池中:task@ 45
创建任务并提交到线程池中:task@ 46
创建任务并提交到线程池中:task@ 47
创建任务并提交到线程池中:task@ 48
创建任务并提交到线程池中:task@ 49
创建任务并提交到线程池中:task@ 50
创建任务并提交到线程池中:task@ 51
创建任务并提交到线程池中:task@ 52
创建任务并提交到线程池中:task@ 53
创建任务并提交到线程池中:task@ 54
创建任务并提交到线程池中:task@ 55
创建任务并提交到线程池中:task@ 56
创建任务并提交到线程池中:task@ 57
创建任务并提交到线程池中:task@ 58
创建任务并提交到线程池中:task@ 59
创建任务并提交到线程池中:task@ 60
创建任务并提交到线程池中:task@ 61
创建任务并提交到线程池中:task@ 62
创建任务并提交到线程池中:task@ 63
创建任务并提交到线程池中:task@ 64
创建任务并提交到线程池中:task@ 65
创建任务并提交到线程池中:task@ 66
创建任务并提交到线程池中:task@ 67
创建任务并提交到线程池中:task@ 68
创建任务并提交到线程池中:task@ 69
创建任务并提交到线程池中:task@ 70
创建任务并提交到线程池中:task@ 71
创建任务并提交到线程池中:task@ 72
创建任务并提交到线程池中:task@ 73
创建任务并提交到线程池中:task@ 74
创建任务并提交到线程池中:task@ 75
创建任务并提交到线程池中:task@ 76
创建任务并提交到线程池中:task@ 77
创建任务并提交到线程池中:task@ 78
创建任务并提交到线程池中:task@ 79
创建任务并提交到线程池中:task@ 80
创建任务并提交到线程池中:task@ 81
创建任务并提交到线程池中:task@ 82
创建任务并提交到线程池中:task@ 83
创建任务并提交到线程池中:task@ 84
创建任务并提交到线程池中:task@ 85
创建任务并提交到线程池中:task@ 86
创建任务并提交到线程池中:task@ 87
创建任务并提交到线程池中:task@ 88
创建任务并提交到线程池中:task@ 89
创建任务并提交到线程池中:task@ 90
创建任务并提交到线程池中:task@ 91
创建任务并提交到线程池中:task@ 92
创建任务并提交到线程池中:task@ 93
创建任务并提交到线程池中:task@ 94
创建任务并提交到线程池中:task@ 95
创建任务并提交到线程池中:task@ 96
创建任务并提交到线程池中:task@ 97
创建任务并提交到线程池中:task@ 98
创建任务并提交到线程池中:task@ 99
创建任务并提交到线程池中:task@ 100
开始执行任务:task@ 35
pool-1-thread-32
开始执行任务:task@ 98
pool-1-thread-1
开始执行任务:task@ 99
pool-1-thread-2
开始执行任务:task@ 100
pool-1-thread-3

从结果中可以看出,有些线程被抛弃了,这和使用的策略有关系。


ExecutorService, Callable, Future, FutureTask

 Java中封装了线程池类,可以使用Executors类来获取几种预定义好的线程池模式。Callable接口与Runnable接口都可以实现多线程,但是Callable可以使线程带有返回值,返回值可以使用Future来获取,这一点有时候很有用。FuturTask同时实现了Runnable, Future<V>接口,可以用来管理线程。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;


public class FutureTest
{
    public static void main(String[] args) throws InterruptedException, ExecutionException
    {
        ExecutorService pool = Executors.newCachedThreadPool();
        List<Future<Integer>> result = new ArrayList<Future<Integer>>();
        
        for (int i=0; i<100; i++)
        {
            MyCompute c = new MyCompute();
            FutureTask<Integer> task = new FutureTask<Integer>(c);
            
            pool.execute(task);
            result.add(task);
        }
        
        pool.shutdown();
        
        int sum = 0;
        for (Future<Integer> f : result)
        {
            Integer i = f.get();
            if (null != i)
            {
                sum += i;
            }
        }
        
        System.out.println(sum);
        
        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) pool;
        System.out.println(threadPool.getLargestPoolSize());
    }

}

class MyCompute implements Callable<Integer>
{

    @Override
    public Integer call() throws Exception
    {
        System.out.println("thread ID: " + Thread.currentThread().getId());
        System.out.println("thread Name: " + Thread.currentThread().getName());
        Thread.sleep(20);
        double d = 1000 * Math.random();
        return (int) d;
    }
    
}

运行结果:

thread ID: 8
thread Name: pool-1-thread-1
thread ID: 9
thread Name: pool-1-thread-2
thread ID: 10
thread Name: pool-1-thread-3
thread ID: 11
thread Name: pool-1-thread-4
thread ID: 12
thread Name: pool-1-thread-5
thread ID: 13
thread Name: pool-1-thread-6
thread ID: 14
thread Name: pool-1-thread-7
thread ID: 15
thread Name: pool-1-thread-8
thread ID: 16
thread Name: pool-1-thread-9
thread ID: 17
thread Name: pool-1-thread-10
thread ID: 18
thread Name: pool-1-thread-11
thread ID: 19
thread Name: pool-1-thread-12
thread ID: 20
thread Name: pool-1-thread-13
thread ID: 21
thread Name: pool-1-thread-14
thread ID: 22
thread Name: pool-1-thread-15
thread ID: 23
thread Name: pool-1-thread-16
thread ID: 24
thread Name: pool-1-thread-17
thread ID: 25
thread Name: pool-1-thread-18
thread ID: 26
thread Name: pool-1-thread-19
thread ID: 27
thread Name: pool-1-thread-20
thread ID: 28
thread Name: pool-1-thread-21
thread ID: 29
thread Name: pool-1-thread-22
thread ID: 30
thread Name: pool-1-thread-23
thread ID: 31
thread Name: pool-1-thread-24
thread ID: 32
thread Name: pool-1-thread-25
thread ID: 33
thread Name: pool-1-thread-26
thread ID: 34
thread Name: pool-1-thread-27
thread ID: 36
thread Name: pool-1-thread-29
thread ID: 37
thread Name: pool-1-thread-30
thread ID: 38
thread Name: pool-1-thread-31
thread ID: 39
thread Name: pool-1-thread-32
thread ID: 40
thread Name: pool-1-thread-33
thread ID: 41
thread Name: pool-1-thread-34
thread ID: 42
thread Name: pool-1-thread-35
thread ID: 43
thread Name: pool-1-thread-36
thread ID: 35
thread Name: pool-1-thread-28
thread ID: 44
thread Name: pool-1-thread-37
thread ID: 45
thread Name: pool-1-thread-38
thread ID: 46
thread Name: pool-1-thread-39
thread ID: 47
thread Name: pool-1-thread-40
thread ID: 48
thread Name: pool-1-thread-41
thread ID: 49
thread Name: pool-1-thread-42
thread ID: 50
thread Name: pool-1-thread-43
thread ID: 21
thread Name: pool-1-thread-14
thread ID: 17
thread Name: pool-1-thread-10
thread ID: 13
thread Name: pool-1-thread-6
thread ID: 16
thread Name: pool-1-thread-9
thread ID: 11
thread Name: pool-1-thread-4
thread ID: 19
thread Name: pool-1-thread-12
thread ID: 14
thread Name: pool-1-thread-7
thread ID: 20
thread Name: pool-1-thread-13
thread ID: 12
thread Name: pool-1-thread-5
thread ID: 10
thread Name: pool-1-thread-3
thread ID: 15
thread Name: pool-1-thread-8
thread ID: 52
thread Name: pool-1-thread-45
thread ID: 9
thread Name: pool-1-thread-2
thread ID: 51
thread Name: pool-1-thread-44
thread ID: 31
thread Name: pool-1-thread-24
thread ID: 30
thread Name: pool-1-thread-23
thread ID: 18
thread Name: pool-1-thread-11
thread ID: 28
thread Name: pool-1-thread-21
thread ID: 23
thread Name: pool-1-thread-16
thread ID: 22
thread Name: pool-1-thread-15
thread ID: 24
thread Name: pool-1-thread-17
thread ID: 25
thread Name: pool-1-thread-18
thread ID: 27
thread Name: pool-1-thread-20
thread ID: 8
thread Name: pool-1-thread-1
thread ID: 26
thread Name: pool-1-thread-19
thread ID: 29
thread Name: pool-1-thread-22
thread ID: 32
thread Name: pool-1-thread-25
thread ID: 53
thread Name: pool-1-thread-46
thread ID: 33
thread Name: pool-1-thread-26
thread ID: 34
thread Name: pool-1-thread-27
thread ID: 37
thread Name: pool-1-thread-30
thread ID: 36
thread Name: pool-1-thread-29
thread ID: 38
thread Name: pool-1-thread-31
thread ID: 39
thread Name: pool-1-thread-32
thread ID: 40
thread Name: pool-1-thread-33
thread ID: 41
thread Name: pool-1-thread-34
thread ID: 43
thread Name: pool-1-thread-36
thread ID: 42
thread Name: pool-1-thread-35
thread ID: 44
thread Name: pool-1-thread-37
thread ID: 35
thread Name: pool-1-thread-28
thread ID: 46
thread Name: pool-1-thread-39
thread ID: 45
thread Name: pool-1-thread-38
thread ID: 47
thread Name: pool-1-thread-40
thread ID: 48
thread Name: pool-1-thread-41
thread ID: 54
thread Name: pool-1-thread-47
thread ID: 66
thread Name: pool-1-thread-59
thread ID: 65
thread ID: 55
thread Name: pool-1-thread-48
thread ID: 56
thread Name: pool-1-thread-49
thread ID: 57
thread Name: pool-1-thread-50
thread ID: 58
thread Name: pool-1-thread-51
thread ID: 59
thread Name: pool-1-thread-52
thread ID: 60
thread Name: pool-1-thread-53
thread ID: 61
thread Name: pool-1-thread-54
thread ID: 62
thread Name: pool-1-thread-55
thread ID: 63
thread Name: pool-1-thread-56
thread ID: 64
thread Name: pool-1-thread-57
thread Name: pool-1-thread-58
50570
59


参考资料:

线程池(java.util.concurrent.ThreadPoolExecutor)的使用(一)

《Java核心技术》


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值