java多线程之 Executors线程池管理

1.  Executors
此类中提供的一些方法有:
1.1 public static ExecutorService newCachedThreadPool()
创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。
 
1.2 public static ExecutorService newFixedThreadPool(int nThreads)
创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
 
1.3 public static ExecutorService newSingleThreadExecutor()
创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
 
这三个方法都可以配合接口ThreadFactory的实例一起使用。并且返回一个ExecutorService接口的实例。
2. 接口 ThreadFactory
根据需要创建新线程的对象。使用线程工厂就无需再手工编写对 new Thread 的调用了,从而允许应用程序使用特殊的线程子类、属性等等。
此接口最简单的实现就是:
class SimpleThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
     return new Thread(r);
   }
 }
3. 接口ExecutorService
该接口提供了管理终止的方法。
4.测试用例:
  4.1固定大小线程:
代码 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
 /**
  * 
  * @author hxm
  *
  */
 public class TestThread {
     public static void main(String args[]){
         //创建一个可重用固定线程数的线程池
         ExecutorService pool = Executors.newFixedThreadPool(4);
         
         //创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
 //        ExecutorService pool = Executors.newSingleThreadExecutor();
         //创建实现了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);
         //关闭线程池
         pool.shutdown();
     }
 }
  class MyThread extends Thread{
      
      @Override
      public void run(){
          System.out.println(Thread.currentThread().getName()+" is running...");
      }
  }
View Code

  4.2单任务线程:

package cn.itcast.heima2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //创建一个线程池
//        ExecutorService threadPool = Executors.newFixedThreadPool(3);//创建3个线程
//        ExecutorService threadPool = Executors.newCachedThreadPool();
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for(int i=1;i<=10;i++){
            final int task = i;
            //往线程池里面添加任务
            threadPool.execute(new Runnable(){
                @Override
                public void run() {
                    for(int j=1;j<=10;j++){
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for  task of " + task);
                    }
                }
            });
        }
        System.out.println("all of 10 tasks have committed! ");
        //定时器
        Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
                new Runnable(){
                    @Override
                public void run() {
                    System.out.println("bombing!");
                    
                }},
                6,
                2,
                TimeUnit.SECONDS);
    }

}
View Code

  4.3 单任务延迟线程:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author hxm
 *
 */
public class TestThread {
    public static void main(String args[]){
        //创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行
        ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
        //创建实现了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.schedule(t4, 10, TimeUnit.MILLISECONDS); 
        pool.schedule(t5, 10, TimeUnit.MILLISECONDS); 

        //关闭线程池
        pool.shutdown();
    }
}
 class MyThread extends Thread{
     
     @Override
     public void run(){
         System.out.println(Thread.currentThread().getName()+" is running...");
     }
 }
View Code

  4.4 自定义线程池:

 import java.util.concurrent.ArrayBlockingQueue;
 2 import java.util.concurrent.BlockingQueue;
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.ScheduledExecutorService;
 6 import java.util.concurrent.ThreadPoolExecutor;
 7 import java.util.concurrent.TimeUnit;
 8 
 9 /**
10  * 
11  * @author hxm
12  *
13  */
14 public class TestThread {
15     public static void main(String args[]){
16           //创建等待队列 
17         BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20); 
18         //创建一个单线程执行程序,它可安排在给定延迟后运行命令或者定期地执行。 
19         ThreadPoolExecutor pool = new ThreadPoolExecutor(2,3,2,TimeUnit.MILLISECONDS,bqueue); 
20 
21         //创建实现了runnable接口的对象
22         Thread t1 = new MyThread();
23         Thread t2 = new MyThread();
24         Thread t3 = new MyThread();
25         Thread t4 = new MyThread();
26         Thread t5 = new MyThread();
27         //将线程放入池中进行执行
28         pool.execute(t1);
29         pool.execute(t2);
30         pool.execute(t3);
31         pool.execute(t4);
32         pool.execute(t5);
33         //关闭线程池
34         pool.shutdown();
35     }
36 }
37  class MyThread extends Thread{
38      
39      @Override
40      public void run(){
41          System.out.println(Thread.currentThread().getName()+" is running...");
42     try { 
43          Thread.sleep(100L); 
44      } catch (InterruptedException e) { 
45              e.printStackTrace(); 
46      } 
47      }
48  }
View Code

 

posted @ 2013-07-12 15:56  若 ♂ 只如初见  阅读(509)  评论(0编辑  收藏  举报