zoukankan      html  css  js  c++  java
  • ExecutorService常用方法和newFixedThreadPool创建固定大小的线程池

    线程池的概念:

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

    (举个简单的例子,线程池就相当于一个水池又或者是一个笔筒,里面放着很多的笔,当有线程任务的时候,就从笔筒去除,用完之后就再次放入进去。)

    个人理解:


    1、在Java5之前,要实现一个线程池是相当有难度的,现在Java5为我们做好了一切,我们只需要按照提供的API来使用,即可享受线程池带来的极大便利。

    2、Java5的线程池分好多种:具体的可以分为两类,固定尺寸的线程池、可变尺寸连接池。

    3、在使用线程池之前,必须知道如何去创建一个线程池,在Java5中,需要了解java.util.concurrent.Executors类的API,这个类提供大量创建连接池的静态方法,是必须掌握的。
    一、固定大小的线程池,newFixedThreadPool:

    package app.executors;  
      
    import java.util.concurrent.Executors;  
    import java.util.concurrent.ExecutorService;  
      
    /** 
     * Java线程:线程池 
     *  
     * @author 冯小卫 
     */  
    public class Test {  
        public static void main(String[] args) {  
            // 创建一个可重用固定线程数的线程池  
            ExecutorService pool = Executors.newFixedThreadPool(5);  
            // 创建线程  
            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() + "正在执行。。。");  
        }  
    }  

    输出结果:

    pool-1-thread-1正在执行。。。  
    pool-1-thread-3正在执行。。。  
    pool-1-thread-4正在执行。。。  
    pool-1-thread-2正在执行。。。  
    pool-1-thread-5正在执行。。。  

    改变ExecutorService pool = Executors.newFixedThreadPool(5)中的参数:ExecutorService pool = Executors.newFixedThreadPool(2),输出结果是:

    pool-1-thread-1正在执行。。。  
    pool-1-thread-1正在执行。。。  
    pool-1-thread-2正在执行。。。  
    pool-1-thread-1正在执行。。。  
    pool-1-thread-2正在执行。。。  

    从以上结果可以看出,newFixedThreadPool的参数指定了可以运行的线程的最大数目,超过这个数目的线程加进去以后,不会运行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。

    二、单任务线程池,newSingleThreadExecutor:

    仅仅是把上述代码中的ExecutorService pool = Executors.newFixedThreadPool(2)改为ExecutorService pool = Executors.newSingleThreadExecutor();

    输出结果:

    pool-1-thread-1正在执行。。。  
    pool-1-thread-1正在执行。。。  
    pool-1-thread-1正在执行。。。  
    pool-1-thread-1正在执行。。。  
    pool-1-thread-1正在执行。。。  

    可以看出,每次调用execute方法,其实最后都是调用了thread-1的run方法。

    三、可变尺寸的线程池,newCachedThreadPool:

    与上面的类似,只是改动下pool的创建方式:ExecutorService pool = Executors.newCachedThreadPool();


    输出:

    pool-1-thread-1正在执行。。。  
    pool-1-thread-2正在执行。。。  
    pool-1-thread-4正在执行。。。  
    pool-1-thread-3正在执行。。。  
    pool-1-thread-5正在执行。。。  

    这种方式的特点是:可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。

    四、延迟连接池,newScheduledThreadPool:

    package app.executors;  
      
    import java.util.concurrent.Executors;  
    import java.util.concurrent.ScheduledExecutorService;  
    import java.util.concurrent.TimeUnit;  
      
    /** 
     * Java线程:线程池 
     *  
     */  
    public class Test {  
        public static void main(String[] args) {  
            // 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。  
            ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);  
            // 创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口  
            Thread t1 = new MyThread();  
            Thread t2 = new MyThread();  
            Thread t3 = new MyThread();  
            // 将线程放入池中进行执行  
            pool.execute(t1);  
            // 使用延迟执行风格的方法  
            pool.schedule(t2, 1000, TimeUnit.MILLISECONDS);  
            pool.schedule(t3, 10, TimeUnit.MILLISECONDS);  
      
            // 关闭线程池  
            pool.shutdown();  
        }  
    }  
      
    class MyThread extends Thread {  
        @Override  
        public void run() {  
            System.out.println(Thread.currentThread().getName() + "正在执行。。。");  
        }  
    }  

    ExecutorService:

    是一个接口,继承了Executor:

    public interface ExecutorService extends Executor {
    }
    2、Executor:

    而Executor亦是一个接口,该接口只包含了一个方法:

    void execute(Runnable command);
    3、Executors:

    该类是一个辅助类,此包中所定义的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 类的工厂和实用方法。

    此类支持以下各种方法:

    • 创建并返回设置有常用配置字符串的 ExecutorService 的方法。 • 创建并返回设置有常用配置字符串的 ScheduledExecutorService 的方法。 • 创建并返回“包装的”ExecutorService 方法,它通过使特定于实现的方法不可访问来禁用重新配置。 • 创建并返回 ThreadFactory 的方法,它可将新创建的线程设置为已知的状态。 • 创建并返回非闭包形式的 Callable 的方法,这样可将其用于需要 Callable 的执行方法中。
    4、创建ExecutorService的方法:
    newFixedThreadPool()

    创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。

    5、ExecutorService的方法:

    shutdown

    void shutdown()
    启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。 
     
    
    抛出:
    SecurityException - 如果安全管理器存在并且关闭,此 ExecutorService 可能操作某些不允许调用者修改的线程(因为它没有保持 RuntimePermission("modifyThread")),或者安全管理器的 checkAccess 方法拒绝访问。
    启动一次顺序关闭,执行以前提交的任务,但不接受新任务。如果已经关闭,则调用没有其他作用。

    awaitTermination

    boolean awaitTermination(long timeout,
                             TimeUnit unit)
                             throws InterruptedException
    请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行。 
     
    
    参数:
    timeout - 最长等待时间
    unit - timeout 参数的时间单位
    返回:
    如果此执行程序终止,则返回 true;如果终止前超时期满,则返回 false
    抛出:
    InterruptedException - 如果等待时发生中断
    请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行。既是等待所有子线程执行结束。

    execute

    void execute(Runnable command)
    在未来某个时间执行给定的命令。该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor实现决定。 
    参数:
    command - 可运行的任务
    抛出:
    RejectedExecutionException - 如果不能接受执行此任务。
    NullPointerException - 如果命令为 null

    在未来某个时间执行给定的命令。该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。

    submit

    Future<?> submit(Runnable task)
    提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在成功 完成时将会返回 null。 
     
    
    参数:
    task - 要提交的任务
    返回:
    表示任务等待完成的 Future
    抛出:
    RejectedExecutionException - 如果任务无法安排执行
    NullPointerException - 如果该任务为 null
    提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在成功 完成时将会返回 null
    6、下面是相关的使用例子:
    public class ExecutorServiceTest {
    
        public static void main(String[] args) throws IOException, InterruptedException {
            // 创建一个固定大小的线程池
            ExecutorService service = Executors.newFixedThreadPool(3);
            for (int i = 0; i < 10; i++) {
                System.out.println("创建线程" + i);
                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("启动线程");
                    }
                };
                // 在未来某个时间执行给定的命令
                service.execute(run);
            }
            // 关闭启动线程
            service.shutdown();
            // 等待子线程结束,再继续执行下面的代码
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            System.out.println("all thread complete");
        }
    }

    可以发现线程被循环创建,但是启动线程却不是连续的,而是由ExecutorService决定的。

  • 相关阅读:
    javaScript系列 [35]HTML页面渲染的基本过程
    javaScript系列 [29] RegExp
    javaScript系列 [40]defineProperty
    javaScript系列 [32] type
    javaScript系列 [34]FormData
    javaScript系列 [39]deepClone
    javaScript系列 [33] new
    javaScript系列 [36]Call by sharing
    javaScript系列 [38]浏览器、HTML和内核(引擎)
    javaScript系列 [28] Event
  • 原文地址:https://www.cnblogs.com/weiyi1314/p/15401416.html
Copyright © 2011-2022 走看看