首页 > 学院 > 开发设计 > 正文

newFixedThreadPool

2019-11-15 01:02:06
字体:
来源:转载
供稿:网友
newFixedThreadPool

newFixedThreadPool内部有个任务队列,假设线程池里有3个线程,提交了5个任务,那么后两个任务就放在任务队列了,即使前3个任务sleep或者堵塞了,也不会执行后两个任务,除非前三个任务有执行完的

newFixedThreadPool使用范例:

java代码收藏代码
  1. importjava.io.IOException;
  2. importjava.util.concurrent.ExecutorService;
  3. importjava.util.concurrent.Executors;
  4. publicclassTest{
  5. publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{
  6. ExecutorServiceservice=Executors.newFixedThreadPool(2);
  7. for(inti=0;i<6;i++){
  8. finalintindex=i;
  9. System.out.PRintln("task:"+(i+1));
  10. Runnablerun=newRunnable(){
  11. @Override
  12. publicvoidrun(){
  13. System.out.println("threadstart"+index);
  14. try{
  15. Thread.sleep(Long.MAX_VALUE);
  16. }catch(InterruptedExceptione){
  17. e.printStackTrace();
  18. }
  19. System.out.println("threadend"+index);
  20. }
  21. };
  22. service.execute(run);
  23. }
  24. }
  25. }

输出:task: 1task: 2thread start0task: 3task: 4task: 5task: 6task: 7thread start1task: 8task: 9task: 10task: 11task: 12task: 13task: 14task: 15

从实例可以看到for循环并没有被固定的线程池阻塞住,也就是说所有的线程task都被提交到了ExecutorService中,查看Executors.newFixedThreadPool()如下:

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

可以看到task被提交都了LinkedBlockingQueue中。这里有个问题,如果任务列表很大,一定会把内存撑爆,如何解决?看下面:

Java代码收藏代码
  1. importjava.io.IOException;
  2. importjava.util.concurrent.ArrayBlockingQueue;
  3. importjava.util.concurrent.BlockingQueue;
  4. importjava.util.concurrent.ThreadPoolExecutor;
  5. importjava.util.concurrent.TimeUnit;
  6. publicclassTest{
  7. publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{
  8. BlockingQueue<Runnable>queue=newArrayBlockingQueue<Runnable>(3);
  9. ThreadPoolExecutorexecutor=newThreadPoolExecutor(3,3,1,TimeUnit.HOURS,queue,newThreadPoolExecutor.CallerRunsPolicy());
  10. for(inti=0;i<10;i++){
  11. finalintindex=i;
  12. System.out.println("task:"+(index+1));
  13. Runnablerun=newRunnable(){
  14. @Override
  15. publicvoidrun(){
  16. System.out.println("threadstart"+(index+1));
  17. try{
  18. Thread.sleep(Long.MAX_VALUE);
  19. }catch(InterruptedExceptione){
  20. e.printStackTrace();
  21. }
  22. System.out.println("threadend"+(index+1));
  23. }
  24. };
  25. executor.execute(run);
  26. }
  27. }
  28. }

输出:task: 1task: 2thread start1task: 3task: 4task: 5task: 6task: 7thread start2thread start7thread start6

线程池最大值为4(??这里我不明白为什么是设置值+1,即3+1,而不是3),准备执行的任务队列为3。可以看到for循环先处理4个task,然后把3个放到队列。这样就实现了自动阻塞队列的效果。记得要使用ArrayBlockingQueue这个队列,然后设置容量就OK了。

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

点击(此处)折叠或打开

  1. packagedemo;
  2. importjava.io.Serializable;
  3. importjava.util.concurrent.ArrayBlockingQueue;
  4. importjava.util.concurrent.ThreadPoolExecutor;
  5. importjava.util.concurrent.TimeUnit;
  6. publicclassTestThreadPool2
  7. {
  8. privatestaticintproduceTaskSleepTime=2;
  9. privatestaticintproduceTaskMaxNumber=10;
  10. publicstaticvoidmain(String[]args)
  11. {
  12. // 构造一个线程池
  13. ThreadPoolExecutorthreadPool=newThreadPoolExecutor(2,4,3,TimeUnit.SECONDS,newArrayBlockingQueue<Runnable>(3),
  14. newThreadPoolExecutor.DiscardOldestPolicy());
  15. for(inti=1;i<=produceTaskMaxNumber;i++)
  16. {
  17. try
  18. {
  19. // 产生一个任务,并将其加入到线程池
  20. Stringtask="task@ "+i;
  21. System.out.println("put "+task);
  22. threadPool.execute(newThreadPoolTask(task));
  23. // 便于观察,等待一段时间
  24. Thread.sleep(produceTaskSleepTime);
  25. }
  26. catch(Exceptione)
  27. {
  28. e.printStackTrace();
  29. }
  30. }
  31. }
  32. }
  33. /**
  34. * 线程池执行的任务
  35. */
  36. classThreadPoolTaskimplementsRunnable,Serializable
  37. {
  38. privatestaticfinallongserialVersionUID=0;
  39. privatestaticintconsumeTaskSleepTime=2000;
  40. // 保存任务所需要的数据
  41. privateObjectthreadPoolTaskData;
  42. ThreadPoolTask(Objecttasks)
  43. {
  44. this.threadPoolTaskData=tasks;
  45. }
  46. publicvoidrun()
  47. {
  48. // 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句
  49. System.out.println(Thread.currentThread().getName());
  50. System.out.println("start .."+threadPoolTaskData);
  51. try
  52. {
  53. // //便于观察,等待一段时间
  54. Thread.sleep(consumeTaskSleepTime);
  55. }
  56. catch(Exceptione)
  57. {
  58. e.printStackTrace();
  59. }
  60. threadPoolTaskData=null;
  61. }
  62. publicObjectgetTask()
  63. {
  64. returnthis.threadPoolTaskData;
  65. }
  66. }

说明:1、在这段程序中,一个任务就是一个Runnable类型的对象,也就是一个ThreadPoolTask类型的对象。2、一般来说任务除了处理方式外,还需要处理的数据,处理的数据通过构造方法传给任务。3、在这段程序中,main()方法相当于一个残忍的领导,他派发出许多任务,丢给一个叫 threadPool的任劳任怨的小组来做。这个小组里面队员至少有两个,如果他们两个忙不过来,任务就被放到任务列表里面。如果积压的任务过多,多到任务列表都装不下(超过3个)的时候,就雇佣新的队员来帮忙。但是基于成本的考虑,不能雇佣太多的队员,至多只能雇佣 4个。如果四个队员都在忙时,再有新的任务,这个小组就处理不了了,任务就会被通过一种策略来处理,我们的处理方式是不停的派发,直到接受这个任务为止(更残忍!呵呵)。因为队员工作是需要成本的,如果工作很闲,闲到 3SECONDS都没有新的任务了,那么有的队员就会被解雇了,但是,为了小组的正常运转,即使工作再闲,小组的队员也不能少于两个。4、通过调整 produceTaskSleepTime和 consumeTaskSleepTime的大小来实现对派发任务和处理任务的速度的控制,改变这两个值就可以观察不同速率下程序的工作情况。5、通过调整4中所指的数据,再加上调整任务丢弃策略,换上其他三种策略,就可以看出不同策略下的不同处理方式。6、对于其他的使用方法,参看jdk的帮助,很容易理解和使用。另一个例子:

点击(此处)折叠或打开

  1. packagedemo;
  2. importjava.util.Queue;
  3. importjava.util.concurrent.ArrayBlockingQueue;
  4. importjava.util.concurrent.ThreadPoolExecutor;
  5. importjava.util.concurrent.TimeUnit;
  6. publicclassThreadPoolExecutorTest
  7. {
  8. privatestaticintqueueDeep=4;
  9. publicvoidcreateThreadPool()
  10. {
  11. /*
  12. * 创建线程池,最小线程数为2,最大线程数为4,线程池维护线程的空闲时间为3秒,
  13. * 使用队列深度为4的有界队列,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,
  14. * 然后重试执行程序(如果再次失败,则重复此过程),里面已经根据队列深度对任务加载进行了控制。
  15. */
  16. ThreadPoolExecutortpe=newThreadPoolExecutor(2,4,3,TimeUnit.SECONDS,newArrayBlockingQueue<Runnable>(queueDeep),
  17. newThreadPoolExecutor.DiscardOldestPolicy());
  18. // 向线程池中添加 10 个任务
  19. for(inti=0;i<10;i++)
  20. {
  21. try
  22. {
  23. Thread.sleep(1);
  24. }
  25. catch(InterruptedExceptione)
  26. {
  27. e.printStackTrace();
  28. }
  29. while(getQueueSize(tpe.getQueue())>=queueDeep)
  30. {
  31. System.out.println("队列已满,等3秒再添加任务");
  32. try
  33. {
  34. Thread.sleep(3000);
  35. }
  36. catch(InterruptedExceptione)
  37. {
  38. e.printStackTrace();
  39. }
  40. }
  41. TaskThreadPool ttp=newTaskThreadPool(i);
  42. System.out.println("put i:"+i);
  43. tpe.execute(ttp);
  44. }
  45. tpe.shutdown();
  46. }
  47. privatesynchronizedintgetQueueSize(Queuequeue)
  48. {
  49. returnqueue.size();
  50. }
  51. publicstaticvoidmain(String[]args)
  52. {
  53. ThreadPoolExecutorTest test=newThreadPoolExecutorTest();
  54. test.createThreadPool();
  55. }
  56. classTaskThreadPoolimplementsRunnable
  57. {
  58. privateintindex;
  59. publicTaskThreadPool(intindex)
  60. {
  61. this.index=index;
  62. }
  63. publicvoidrun()
  64. {
  65. System.out.println(Thread.currentThread()+" index:"+index);
  66. try
  67. {
  68. Thread.sleep(3000);
  69. }
  70. catch(InterruptedExceptione)
  71. {
  72. e.printStackTrace();
  73. }
  74. }
  75. }
  76. }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表