现在的位置: 首页 > java > j2se > 正文
使用Executors创建和管理线程
2012年08月02日 j2se ⁄ 共 9012字 暂无评论

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 的调用了,从而允许应用程序使用特殊的线程子类、属性等等。
此接口最简单的实现就是:

  1. class SimpleThreadFactory implements ThreadFactory {   
  2.    public Thread newThread(Runnable r) {   
  3.      return new Thread(r);   
  4.    }   
  5.  }  
  6. 3. 接口ExecutorService
    该接口提供了管理终止的方法。
    4.创建标准线程池启动线程
    4.1 提供一个简单的实现Runnable接口的线程
    MyThread.java
    1. package com.zj.concurrency.executors;   
    2.     
    3. public class MyThread implements Runnable {   
    4.     private int count = 1, number;   
    5.     
    6.     public MyThread(int num) {   
    7.        number = num;   
    8.        System.out.println("Create Thread-" + number);   
    9.     }   
    10.     
    11.     public void run() {   
    12.        while (true) {   
    13.            System.out.println("Thread-" + number + " run " + count+" time(s)");   
    14.            if (++count == 3)   
    15.               return;   
    16.        }   
    17.     }   
    18. }  这个线程会打印出相应的创建和执行信息。
      4.2使用CachedThreadPool启动线程
      CachedThreadPool.java
      1. package com.zj.concurrency.executors;   
      2. import java.util.concurrent.ExecutorService;   
      3. import java.util.concurrent.Executors;   
      4.     
      5. public class CachedThreadPool {   
      6.     public static void main(String[] args) {   
      7.        ExecutorService exec = Executors.newCachedThreadPool();   
      8.        for (int i = 0; i < 5; i++)   
      9.            exec.execute(new MyThread(i));   
      10.        exec.shutdown();   
      11.     }   
      12. }  
      13. 结果:
        Create Thread-0
        Create Thread-1
        Create Thread-2
        Create Thread-3
        Thread-0 run 1 time(s)
        Thread-0 run 2 time(s)
        Thread-1 run 1 time(s)
        Thread-1 run 2 time(s)
        Thread-2 run 1 time(s)
        Thread-2 run 2 time(s)
        Create Thread-4
        Thread-4 run 1 time(s)
        Thread-4 run 2 time(s)
        Thread-3 run 1 time(s)
        Thread-3 run 2 time(s)

        4.3 使用FixedThreadPool启动线程
        FixedThreadPool.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors;   
        2. import java.util.concurrent.ExecutorService;   
        3. import java.util.concurrent.Executors;   
        4.     
        5. public class FixedThreadPool {   
        6.     public static void main(String[] args) {   
        7.        ExecutorService exec = Executors.newFixedThreadPool(2);   
        8.        for (int i = 0; i < 5; i++)   
        9.            exec.execute(new MyThread(i));   
        10.        exec.shutdown();   
        11.     }   
        12. }  
        package com.zj.concurrency.executors;
        import java.util.concurrent.ExecutorService;
        import java.util.concurrent.Executors;
        
        public class FixedThreadPool {
            public static void main(String[] args) {
               ExecutorService exec = Executors.newFixedThreadPool(2);
               for (int i = 0; i < 5; i++)
                   exec.execute(new MyThread(i));
               exec.shutdown();
            }
        }

        结果:
        Create Thread-0
        Create Thread-1
        Create Thread-2
        Create Thread-3
        Create Thread-4
        Thread-0 run 1 time(s)
        Thread-0 run 2 time(s)
        Thread-2 run 1 time(s)
        Thread-2 run 2 time(s)
        Thread-3 run 1 time(s)
        Thread-3 run 2 time(s)
        Thread-4 run 1 time(s)
        Thread-4 run 2 time(s)
        Thread-1 run 1 time(s)
        Thread-1 run 2 time(s)

        4.4 使用SingleThreadExecutor启动线程
        SingleThreadExecutor.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors;   
        2. import java.util.concurrent.ExecutorService;   
        3. import java.util.concurrent.Executors;   
        4.     
        5. public class SingleThreadExecutor {   
        6.     public static void main(String[] args) {   
        7.        ExecutorService exec = Executors.newSingleThreadExecutor();   
        8.        for (int i = 0; i < 5; i++)   
        9.            exec.execute(new MyThread(i));   
        10.        exec.shutdown();   
        11.     }   
        12. }  
        package com.zj.concurrency.executors;
        import java.util.concurrent.ExecutorService;
        import java.util.concurrent.Executors;
        
        public class SingleThreadExecutor {
            public static void main(String[] args) {
               ExecutorService exec = Executors.newSingleThreadExecutor();
               for (int i = 0; i < 5; i++)
                   exec.execute(new MyThread(i));
               exec.shutdown();
            }
        }

        结果:
        Create Thread-0
        Create Thread-1
        Create Thread-2
        Create Thread-3
        Create Thread-4
        Thread-0 run 1 time(s)
        Thread-0 run 2 time(s)
        Thread-1 run 1 time(s)
        Thread-1 run 2 time(s)
        Thread-2 run 1 time(s)
        Thread-2 run 2 time(s)
        Thread-3 run 1 time(s)
        Thread-3 run 2 time(s)
        Thread-4 run 1 time(s)
        Thread-4 run 2 time(s)
        5.配合ThreadFactory接口的使用
        我们试图给线程加入daemon和priority的属性设置。
        5.1设置后台线程属性
        DaemonThreadFactory.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors.factory;   
        2. import java.util.concurrent.ThreadFactory;   
        3.     
        4. public class DaemonThreadFactory implements ThreadFactory {   
        5.     public Thread newThread(Runnable r) {   
        6.        Thread t = new Thread(r);   
        7.        t.setDaemon(true);   
        8.        return t;   
        9.     }   
        10. }  
        package com.zj.concurrency.executors.factory;
        import java.util.concurrent.ThreadFactory;
        
        public class DaemonThreadFactory implements ThreadFactory {
            public Thread newThread(Runnable r) {
               Thread t = new Thread(r);
               t.setDaemon(true);
               return t;
            }
        }

        5.2 设置优先级属性
        最高优先级MaxPriorityThreadFactory.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors.factory;   
        2. import java.util.concurrent.ThreadFactory;   
        3.     
        4. public class MaxPriorityThreadFactory implements ThreadFactory {   
        5.     public Thread newThread(Runnable r) {   
        6.        Thread t = new Thread(r);   
        7.        t.setPriority(Thread.MAX_PRIORITY);   
        8.        return t;   
        9.     }   
        10. }  
        package com.zj.concurrency.executors.factory;
        import java.util.concurrent.ThreadFactory;
        
        public class MaxPriorityThreadFactory implements ThreadFactory {
            public Thread newThread(Runnable r) {
               Thread t = new Thread(r);
               t.setPriority(Thread.MAX_PRIORITY);
               return t;
            }
        }

        最低优先级MinPriorityThreadFactory.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors.factory;   
        2. import java.util.concurrent.ThreadFactory;   
        3.     
        4. public class MinPriorityThreadFactory implements ThreadFactory {   
        5.     public Thread newThread(Runnable r) {   
        6.        Thread t = new Thread(r);   
        7.        t.setPriority(Thread.MIN_PRIORITY);   
        8.        return t;   
        9.     }   
        10. }  
        package com.zj.concurrency.executors.factory;
        import java.util.concurrent.ThreadFactory;
        
        public class MinPriorityThreadFactory implements ThreadFactory {
            public Thread newThread(Runnable r) {
               Thread t = new Thread(r);
               t.setPriority(Thread.MIN_PRIORITY);
               return t;
            }
        }

        5.3启动带有属性设置的线程
        ExecFromFactory.java

        Java代码 复制代码 收藏代码
        1. package com.zj.concurrency.executors;   
        2. import java.util.concurrent.ExecutorService;   
        3. import java.util.concurrent.Executors;   
        4. import com.zj.concurrency.executors.factory.DaemonThreadFactory;   
        5. import com.zj.concurrency.executors.factory.MaxPriorityThreadFactory;   
        6. import com.zj.concurrency.executors.factory.MinPriorityThreadFactory;   
        7.     
        8. public class ExecFromFactory {   
        9.     public static void main(String[] args) throws Exception {   
        10.        ExecutorService defaultExec = Executors.newCachedThreadPool();   
        11.        ExecutorService daemonExec = Executors   
        12.               .newCachedThreadPool(new DaemonThreadFactory());   
        13.        ExecutorService maxPriorityExec = Executors   
        14.               .newCachedThreadPool(new MaxPriorityThreadFactory());   
        15.        ExecutorService minPriorityExec = Executors   
        16.               .newCachedThreadPool(new MinPriorityThreadFactory());   
        17.        for (int i = 0; i < 10; i++)   
        18.            daemonExec.execute(new MyThread(i));   
        19.        for (int i = 10; i < 20; i++)   
        20.            if (i == 10)   
        21.               maxPriorityExec.execute(new MyThread(i));   
        22.            else if (i == 11)   
        23.               minPriorityExec.execute(new MyThread(i));   
        24.            else  
        25.               defaultExec.execute(new MyThread(i));   
        26.     }   
        27. }  
        package com.zj.concurrency.executors;
        import java.util.concurrent.ExecutorService;
        import java.util.concurrent.Executors;
        import com.zj.concurrency.executors.factory.DaemonThreadFactory;
        import com.zj.concurrency.executors.factory.MaxPriorityThreadFactory;
        import com.zj.concurrency.executors.factory.MinPriorityThreadFactory;
        
        public class ExecFromFactory {
            public static void main(String[] args) throws Exception {
               ExecutorService defaultExec = Executors.newCachedThreadPool();
               ExecutorService daemonExec = Executors
                      .newCachedThreadPool(new DaemonThreadFactory());
               ExecutorService maxPriorityExec = Executors
                      .newCachedThreadPool(new MaxPriorityThreadFactory());
               ExecutorService minPriorityExec = Executors
                      .newCachedThreadPool(new MinPriorityThreadFactory());
               for (int i = 0; i < 10; i++)
                   daemonExec.execute(new MyThread(i));
               for (int i = 10; i < 20; i++)
                   if (i == 10)
                      maxPriorityExec.execute(new MyThread(i));
                   else if (i == 11)
                      minPriorityExec.execute(new MyThread(i));
                   else
                      defaultExec.execute(new MyThread(i));
            }
        }

        结果:
        Create Thread-0
        Create Thread-1
        Create Thread-2
        Create Thread-3
        Thread-0 run 1 time(s)
        Thread-0 run 2 time(s)
        Thread-1 run 1 time(s)
        Thread-1 run 2 time(s)
        Thread-2 run 1 time(s)
        Thread-2 run 2 time(s)
        Create Thread-4
        Thread-4 run 1 time(s)
        Thread-4 run 2 time(s)
        Create Thread-5
        Thread-5 run 1 time(s)
        Thread-5 run 2 time(s)
        Create Thread-6
        Create Thread-7
        Thread-7 run 1 time(s)
        Thread-7 run 2 time(s)
        Create Thread-8
        Thread-8 run 1 time(s)
        Thread-8 run 2 time(s)
        Create Thread-9
        Create Thread-10
        Thread-10 run 1 time(s)
        Thread-10 run 2 time(s)
        Create Thread-11
        Thread-9 run 1 time(s)
        Thread-9 run 2 time(s)
        Thread-6 run 1 time(s)
        Thread-6 run 2 time(s)
        Thread-3 run 1 time(s)
        Thread-3 run 2 time(s)
        Create Thread-12
        Create Thread-13
        Create Thread-14
        Thread-12 run 1 time(s)
        Thread-12 run 2 time(s)
        Thread-13 run 1 time(s)
        Thread-13 run 2 time(s)
        Create Thread-15
        Thread-15 run 1 time(s)
        Thread-15 run 2 time(s)
        Create Thread-16
        Thread-16 run 1 time(s)
        Thread-16 run 2 time(s)
        Create Thread-17
        Create Thread-18
        Create Thread-19
        Thread-14 run 1 time(s)
        Thread-14 run 2 time(s)
        Thread-17 run 1 time(s)
        Thread-17 run 2 time(s)
        Thread-18 run 1 time(s)
        Thread-18 run 2 time(s)
        Thread-19 run 1 time(s)
        Thread-19 run 2 time(s)
        Thread-11 run 1 time(s)
        Thread-11 run 2 time(s)

      14.   出自:http://zhangjunhd.blog.51cto.com/113473/70068

 

给我留言

您必须 [ 登录 ] 才能发表留言!

×