线程池ExecutorService和BlockingQueue

线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理。当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程对象所带来的性能开销,节省了系统的资源。

java常用的线程池有四种:

  • newFixedThreadPool

创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。在任意点,在大多数 nThreads 线程会处于处理任务的活动状态。如果在所有线程处于活动状态时提交附加任务,则在有可用线程之前,附加任务将在队列中等待。如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线程将代替它执行后续的任务(如果需要)。在某个线程被显式地关闭之前,池中的线程将一直存在。
  ExecutorService pool = Executors.newFixedThreadPool(2);
  //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
  Thread t1 = new MyThread();
  Thread t2 = new MyThread();
  Thread t3 = new MyThread();
  Thread t4 = new MyThread();
  Thread t5 = new MyThread();
  //将线程放入池中进行执行
  pool.execute(t1);
  pool.execute(t2);
  pool.execute(t3);
  pool.execute(t4);
  pool.execute(t5);

  • newSingleThreadExecutor

创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。(注意,如果因为在关闭前的执行期间出现失败而终止了此单个线程,那么如果需要,一个新线程将代替它执行后续的任务)。可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的。与其他等效的 newFixedThreadPool(1) 不同,可保证无需重新配置此方法所返回的执行程序即可使用其他的线程。

  • newCachedThreadPool

创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。因此,长时间保持空闲的线程池不会使用任何资源。注意,可以使用 ThreadPoolExecutor 构造方法创建具有类似属性但细节不同(例如超时参数)的线程池。

      ScheduledThreadPool

调度型线程池,
  8 public class TestScheduledThread 
 9 

10     public static void
 main(String[] args) 
11 
    { 
12         final
 ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(2); 
13         final Runnable beeper = new
 Runnable() 
14 
        { 
15             int
 count = 0; 
16             public void
 run() 
17 
            { 
18                 System.out.println(new
 Date() + "beep "+ (++count));
19 
            } 
20         }; // 1
秒钟后运行,并每隔2秒运行一次
21         final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate( beeper, 1, 2, SECONDS);
22         // 2
秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行 
23
         final ScheduledFuture beeperHandle2 = scheduler .scheduleWithFixedDelay(beeper, 2, 5, SECONDS); 
24         // 30
秒后结束关闭任务,并且关闭Scheduler 
25
         scheduler.schedule(
26             new
 Runnable() 
27 
            {
28                 public void
 run() 
29 
                { 
30                     beeperHandle.cancel(true
);
31                     beeperHandle2.cancel(true
);
32 
                    scheduler.shutdown(); 
33 
                } 
34 
            }, 30, SECONDS); 
35 
    } 
36 }

ExecutorService submit(Runnable x) execute(Runnable x) 两个方法的的本质区别:

publicclass RunnableTestMain {
 
    publicstaticvoid main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        
        /**
         * execute(Runnable x) 没有返回值。可以执行任务,但无法判断任务是否成功完成。
         */
        pool.execute(new RunnableTest("Task1")); 
        
        /**
         * submit(Runnable x) 返回一个future。可以用这个future来判断任务是否成功完成。请看下面:
         */
        Future future = pool.submit(new RunnableTest("Task2"));
        
        try {
            if(future.get()==null){//如果Future's get返回null,任务完成
                System.out.println("任务完成");
            }
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
            //否则我们可以看看任务失败的原因是什么
            System.out.println(e.getCause().getMessage());
        }
 
    }
 
}
 
publicclass RunnableTest implements Runnable {
    
    private String taskName;
    
    public RunnableTest(final String taskName) {
        this.taskName = taskName;
    }
 
    @Override
    publicvoid run() {
        System.out.println("Inside "+taskName);
        thrownew RuntimeException("RuntimeException from inside " + taskName);
    }
 
}
 
 

本例介绍一个特殊的队列:BlockingQueue,如果BlockQueue是空的,BlockingQueue取东西的操作将会被阻断进入等待状态,直到BlockingQueue进了东西才会被唤醒.同样,如果BlockingQueue是满的,任何试图往里存东西的操作也会被阻断进入等待状态,直到BlockingQueue里有空间才会被唤醒继续操作.

    本例再次实现11.4线程----条件Condition中介绍的篮子程序,不过这个篮子中最多能放的苹果数不是1,可以随意指定.当篮子满时,生产者进入等待状态,当篮子空时,消费者等待.

使用BlockingQueue的关键技术点如下:

    1.BlockingQueue定义的常用方法如下:

        1)add(anObject):anObject加到BlockingQueue,即如果BlockingQueue可以容纳,则返回true,否则招聘异常

        2)offer(anObject):表示如果可能的话,anObject加到BlockingQueue,即如果BlockingQueue可以容纳,则返回true,否则返回false.

        3)put(anObject):anObject加到BlockingQueue,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续.

        4)poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null

        5)take():取走BlockingQueue里排在首位的对象,BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止

    2.BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类

        1)ArrayBlockingQueue:规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的.

        2)LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的

        3)PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序.

        4)SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的.

    3.LinkedBlockingQueueArrayBlockingQueue比较起来,它们背后所用的数据结构不一样,导致LinkedBlockingQueue的数据吞吐量要大于ArrayBlockingQueue,但在线程数量很大时其性能的可预见性低于ArrayBlockingQueue.         

publicclass BlockingQueueTest {

       /**定义装苹果的篮子*/

       publicstaticclass Basket{

              //篮子,能够容纳3个苹果

              BlockingQueue<String> basket = new ArrayBlockingQueue<String>(3);

              //生产苹果,放入篮子

              publicvoid produce() throws InterruptedException{

                     //put方法放入一个苹果,basket满了,等到basket有位置

                     basket.put("An apple");

              }

              //消费苹果,从篮子中取走

              public String consume() throws InterruptedException{

                     //take方法取出一个苹果,basket为空,等到basket有苹果为止

                     returnbasket.take();

              }

       }

       //测试方法

       publicstaticvoid testBasket(){

              final Basket basket = new Basket();//建立一个装苹果的篮子

              //定义苹果生产者

              class Producer implements Runnable{

                     publicvoid run(){

                            try{

                                   while(true){

                                          //生产苹果

                                          System.out.println("生产者准备生产苹果: " + System.currentTimeMillis());

                                          basket.produce();

                                          System.out.println("生产者生产苹果完毕: " + System.currentTimeMillis());

                                          //休眠300ms

                                          Thread.sleep(300);

                                   }

                            }catch(InterruptedException ex){

                            }

                     }

              }

              //定义苹果消费者

              class Consumer implements Runnable{

                     publicvoid run(){

                            try{

                                   while(true){

                                          //消费苹果

                                          System.out.println("消费者准备消费苹果: " + System.currentTimeMillis());

                                          basket.consume();

                                          System.out.println("消费者消费苹果完毕: " + System.currentTimeMillis());

                                          //休眠1000ms

                                          Thread.sleep(1000);

                                   }

                            }catch(InterruptedException ex){

                            }

                     }

              }

              ExecutorService service = Executors.newCachedThreadPool();

              Producer producer = new Producer();

              Consumer consumer = new Consumer();

              service.submit(producer);

              service.submit(consumer);

              //程序运行5s,所有任务停止

              try{

                     Thread.sleep(5000);

              }catch(InterruptedException ex){

              }

              service.shutdownNow();

       }

       publicstaticvoid main(String[] args){

              BlockingQueueTest.testBasket();

       }

}

 
 

 

你可能感兴趣的:(java)