JAVA线程池 newSingleThreadExecutor,newFixedThreadPool,newCachedThreadPool,newScheduledThreadPool(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luohaiqing123456/article/details/52231063
线程池
1. newSingleThreadExecutor
创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
2.newFixedThreadPool
创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
3. newCachedThreadPool
创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。

4.newScheduledThreadPool

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

package com.icardpay.business.quartz.test.dao;


import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class ThreadPoolTest {
private static AtomicInteger line = new AtomicInteger(0);
//定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
static ExecutorService pool = Executors.newFixedThreadPool(100);
// 创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。
static ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
public static int getLine(){
return line.addAndGet(1000);
}
//(一)测试FixedThreadPool
public static void doFixedThreadPoolJob() throws InterruptedException{
for (int i = 0;i<100;i++){
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程:" + Thread.currentThread().getName());
Integer num = ThreadPoolTest.getLine();
System.out.println("startline = " +(num-1000)+",endline = " + num);
}
});
}
pool.shutdown();
System.out.println("shutdown():启动一次顺序关闭,执行以前提交的任务,但不接受新任务。"); 
//判断线程池中线程是否全部执行完毕(注意注意!!!!!!!!!!!!!!)
while(true){  
if(pool.isTerminated()){  
System.out.println("所有的子线程都结束了!");  
break;  
}  
Thread.sleep(1000);    

}
//(二)测试ScheduledThreadPool
/* 不管任务执行耗时是否大于间隔时间,scheduleAtFixedRate和scheduleWithFixedDelay都不会导致同一个任务并发地被执行。唯一不同的是scheduleWithFixedDelay是当前一个任务结束的时刻,开始结算间隔时间,如0秒开始执行第一次任务,任务耗时5秒,任务间隔时间3秒,
那么第二次任务执行的时间是在第8秒开始*/
public static void doScheduledThreadPoolJob() throws InterruptedException{
scheduleAtFixedRate(service,1000);
scheduleAtFixedRate(service,6000);


scheduleWithFixedDelay(service,1000);
scheduleWithFixedDelay(service,6000);
}
/**
* scheduleAtFixedRate(Runnable command,
                                       long initialDelay,
                                       long period,
                                       TimeUnit unit)创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;
                                       也就是将在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,
                                       接着在 initialDelay + 2 * period 后执行,依此类推。如果任务的任何一个执行遇到异常,则后续执行都会被取消。
                                       否则,只能通过执行程序的取消或终止方法来终止该任务。如果此任务的任何一个执行要花费比其周期更长的时间,则将推迟后续执行,但不会同时执行。 
* @param service
* @param sleepTime
*/
private static void scheduleAtFixedRate(ScheduledExecutorService service, final int sleepTime){
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long start = new Date().getTime();
System.out.println("线程"+Thread.currentThread().getName()+"scheduleAtFixedRate 开始执行时间:" +
DateFormat.getTimeInstance().format(new Date()));
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = new Date().getTime();
System.out.println("线程"+Thread.currentThread().getName()+"scheduleAtFixedRate 执行花费时间=" + (end -start)/1000 + "m");
System.out.println("线程"+Thread.currentThread().getName()+"scheduleAtFixedRate 执行完成时间:"
+ DateFormat.getTimeInstance().format(new Date()));
System.out.println("======================================");
}
},1000,5000,TimeUnit.MILLISECONDS);
}
/**
* scheduleWithFixedDelay(Runnable command,
                                          long initialDelay,
                                          long delay,
                                          TimeUnit unit)
                                          创建并执行一个在给定初始延迟后首次启用的定期操作,随后,
                                          在每一次执行终止和下一次执行开始之间都存在给定的延迟。如果任务的任一执行遇到异常,就会取消后续执行。
                                          否则,只能通过执行程序的取消或终止方法来终止该任务。
* @param service
* @param sleepTime
*/
private static void scheduleWithFixedDelay(ScheduledExecutorService service,final int sleepTime){
service.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
long start = new Date().getTime();
System.out.println("scheduleWithFixedDelay 开始执行时间:" +
DateFormat.getTimeInstance().format(new Date()));
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = new Date().getTime();
System.out.println("scheduleWithFixedDelay执行花费时间=" + (end -start)/1000 + "m");
System.out.println("scheduleWithFixedDelay执行完成时间:"
+ DateFormat.getTimeInstance().format(new Date()));
System.out.println("======================================");
}
},1000,5000,TimeUnit.MILLISECONDS);
}


public static void main(String[] args) throws InterruptedException {
ThreadPoolTest.doFixedThreadPoolJob();
System.out.println("任务完成");
ThreadPoolTest.doScheduledThreadPoolJob();
}
}

猜你喜欢

转载自blog.csdn.net/luohaiqing123456/article/details/52231063