java并发编程(十六)----(线程池)java线程池的使用

上节我们简单介绍了线程池,这次我们就来使用一下。Executors提供四种线程池,分别是:newCachedThreadPool,newFixedThreadPool ,newScheduledThreadPool ,newSingleThreadExecutor 。下面我们分别来使用下。

1. newSingleThreadExecutor

创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

我们来看一个小例子:

public class newSingleThreadExecutorTest {
        public static void main(String[] args) {
            ExecutorService ex = Executors.newSingleThreadExecutor();
            for(int i=0;i<10;i++){
                ex.execute(new Runnable() {
                    @Override
                    public void run() {                                         System.out.println(Thread.currentThread().getName());                                                      
                    }
                });
            }
        }
    }

输出为:

pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1

由输出结果可以看出始终只有一个线程在工作。

2. newFixedThreadPool

创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。

我们来看一个小例子:

public class newFixedThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService ex = Executors.newFixedThreadPool(5);
            for(int i=0;i<10;i++){
                ex.execute(new Runnable() {
                    @Override
                    public void run() {
                           System.out.println(Thread.currentThread().getName());
                    }
                });
            }
        }
    }

输出为:

pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
pool-1-thread-5
pool-1-thread-3
pool-1-thread-3
pool-1-thread-3
pool-1-thread-3
pool-1-thread-3
pool-1-thread-4

我们启动了10个线程,但是池中只有5个线程工作,所以结果中最多只有5个线程。

3. newCachedThreadPool

创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。

我们来看一个小例子:

public class newCachedThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService ex = Executors.newCachedThreadPool();
            for(int i=0;i<10;i++){
                ex.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                    }
                });
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

输出为:

pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。但是如果执行第二个任务时第一个任务没有完成则又是另一番景象,我们把上面的例子稍稍改一下就有所不同:

public class newCachedThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService ex = Executors.newCachedThreadPool();
            for(int i=0;i<10;i++){
                ex.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(6000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

输出为:

pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-6
pool-1-thread-7
pool-1-thread-8
pool-1-thread-9
pool-1-thread-10

第一个任务在执行的时候等待了6秒,所以此时第二个任务执行的时候则是新建一个线程来执行。

4. newScheduledThreadPool

创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

在上一篇类类的关系图中我们可以看到该方法直接实现了ScheduledExecutorService接口,而该接口相当于提供了”延时”和”周期执行”功能的ExecutorService,再来看一下该方法的源码:

public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }

返回值是ScheduledExecutorService类型的,与其他3个方法不同,需要注意。我们来看一个小例子:

public class newScheduledThreadPoolTest {
        public static void main(String[] args) {
            ScheduledExecutorService ex = Executors.newScheduledThreadPool(5);
            for(int i=0;i<10;i++){
                ex.schedule(new Runnable() { //定时执行的线程池
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(6000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                },2, TimeUnit.SECONDS); 
            }
        }
    }

输出结果为:

pool-1-thread-2
pool-1-thread-4
pool-1-thread-1
pool-1-thread-5
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-5
pool-1-thread-1
pool-1-thread-4

启动后会延迟2s之后才开始执行。

我们再来看一个周期性执行的例子:

public class newScheduledThreadPoolTest {
        public static void main(String[] args) {
            ScheduledExecutorService ex = Executors.newScheduledThreadPool(5);
            for(int i=0;i<10;i++){
                ex.scheduleAtFixedRate(new Runnable() { //延迟3s后每2s周期性执行一次,不停
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(6000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                },3,2, TimeUnit.SECONDS);
            }
        }
    }

输出为:

pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-5
pool-1-thread-1
...

newScheduledThreadPool中有很多另外3个类中没有的方法,我们来看一下:

  1. shedule(Runnable command, long delay, TimeUnit unit): 延迟一定时间后执行Runnable任务;

  2. schedule(Callable callable, long delay, TimeUnit unit): 延迟一定时间后执行Callable任务;

  3. scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit): 延迟一定时间后,以间隔period时间的频率周期性地执行任务;

  4. scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit): 与scheduleAtFixedRate()方法很类似,但是不同的是scheduleWithFixedDelay()方法的周期时间间隔是以上一个任务执行结束到下一个任务开始执行的间隔,而scheduleAtFixedRate()方法的周期时间间隔是以上一个任务开始执行到下一个任务开始执行的间隔,也就是这一些任务系列的触发时间都是可预知的。

由上我们看到ScheduledExecutorService在执行定时任务方面还是挺强大的。线程池的使用我们就到这里,其实用了这么多我们只是在调用别人写好的方法,但是对于线程池是如何实现的我们还是未知的,下一节我们就深入的去分析线程池的实现,看看到底有什么高深莫测。

原文地址:https://www.cnblogs.com/rickiyang/p/11074254.html