newCachedThreadPool用法
代码
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestMain { public static void main(String[] args) { ExecutorService cachedService = Executors.newCachedThreadPool(); for( int i = 0; i < 100; i ++) { cachedService.execute(new MyThread(i)); } cachedService.shutdown(); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(" Thread-" + Thread.currentThread().getName() + " " + index);; try { Thread.sleep(1000); } catch (Exception e) { } } } }
输出
特点
- 会根据需要创建新线程,如果线程池中有可复用的,会先服用可用的。
- 这个线程池典型的场景是改善 任务耗时短小的 异步任务。
- 使用execute可以复用可用的线程。如果没有可用线程,会创建新线程并添加到线程池里。
- 那些1分钟没有被使用的线程将被停止并从缓存里移除。
newCachedThreadPool实现
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
可知
- corePoolSize 为 0
- maxPoolSize 为 Integer.MAX_VALUE。 无限大
- keepAliveTime为 60 秒,便是 maxPoolSize - corePoolSize的那些线程可以存活的idle时间
newFixedThreadPool(int threadCount)
代码
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestMain { public static void main(String[] args) { // case 2 -------------------------------- ExecutorService fixedService2 = Executors.newFixedThreadPool(5); for ( int i = 0; i < 20; i ++) { fixedService2.execute(new MyThread(i)); } } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(" Thread-" + Thread.currentThread().getName() + " " + index);; try { Thread.sleep(1000); } catch (Exception e) { } } } }
输出
特点
- 可以复用指定数目的线程
- 如果请求的线程数目大于目前idle的,那么多余的请求将被等待,直到线程池中有可用的线程。
- 如果有任何线程执行过程中停止了,将会新建一个线程代替。
- 线程池中的线程一直存活,直到显式的使用shutdown关闭。
newFixedThreadPool实现
可知public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
- corePoolSize 为指定大小
- maxPoolSize 也为指定大小
- keepAliveTime 为0,因为corePoolSize 与 maxPoolSize相同,所以并不影响
newScheduledThreadPool
定时延迟 + 循环执行 实例代码
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) { int j = 0; // case 3 ------------------------------- System.out.println( " " + getDateStr() + " start "); ScheduledExecutorService scheduledService3 = Executors.newScheduledThreadPool(1); scheduledService3.scheduleAtFixedRate(new MyThread(j++), 5, 20, TimeUnit.SECONDS); scheduledService3.scheduleAtFixedRate(new MyThread(j++), 3, 20, TimeUnit.SECONDS); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " "); } } public static String getDateStr() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
输出
延迟执行
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) { int j = 0; // case 3 ------------------------------- System.out.println( " " + getDateStr() + " start "); ScheduledExecutorService scheduledService3 = Executors.newScheduledThreadPool(1); scheduledService3.schedule(new MyThread(j++), 5, TimeUnit.SECONDS); scheduledService3.schedule(new MyThread(j++), 15, TimeUnit.SECONDS); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " "); } } public static String getDateStr() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
输出
newScheduledThreadPool的实现
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
scheduleAtFixedRate特点
关于scheduleAtFixedRate schedule的时间并不受所执行时间长短的影响
- 支持定时及循环任务执行
- 延迟定时,延迟的时间间隔是从调用开始开始计算的,并不受线程执行时间长短的影响
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) { int j = 0; // case 3 ------------------------------- System.out.println( " " + getDateStr() + " start "); ScheduledExecutorService scheduledService3 = Executors.newScheduledThreadPool(1); scheduledService3.scheduleAtFixedRate(new MyThread(j++), 10, 10, TimeUnit.SECONDS); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " +++++"); try { Thread.sleep(8000); } catch (Exception e) { } System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " -----"); } } public static String getDateStr() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
输出
scheduleWithFixedDelay:线程执行完毕开始计算,指定的delay的时间后执行
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) { int j = 0; // case 3 ------------------------------- System.out.println( " " + getDateStr() + " start "); ScheduledExecutorService scheduledService3 = Executors.newScheduledThreadPool(1); scheduledService3.scheduleWithFixedDelay(new MyThread(j++), 10, 10, TimeUnit.SECONDS); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " +++++"); try { Thread.sleep(8000); } catch (Exception e) { } System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() + " -----"); } } public static String getDateStr() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
输出
newSingleThreadScheduledExecutor
代码
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestMain { public static void main(String[] args) { // case 4 ------------------------------- int a = 0; ExecutorService singleThreadService = Executors.newSingleThreadExecutor(); singleThreadService.execute(new MyThread(a++)); singleThreadService.execute(new MyThread(a++)); singleThreadService.execute(new MyThread(a++)); } public static class MyThread implements Runnable { public int index; public MyThread (int index) { this.index = index; } @Override public void run() { System.out.println(index + " " + getDateStr() + " Thread-" + Thread.currentThread().getName() ); try { Thread.sleep(1000); } catch (Exception e) { } } } public static String getDateStr() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
输出
实现
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
特点
- corePoolSize = 1 maxPoolSize = 1;
- 最多只开启一个线程,对于队列中的Runnable,挨个执行
线程池的关闭
shutdown代码
int a = 0; ExecutorService singleThreadService = Executors.newSingleThreadExecutor(); singleThreadService.execute(new MyThread(a++)); singleThreadService.execute(new MyThread(a++)); singleThreadService.execute(new MyThread(a++)); System.out.println("main " + getDateStr() + " shutdown "); singleThreadService.shutdown();
shutdown输出
shutdown特点
- 等待已经有的线程执行完毕
- 新附加的任务不再执行
四种实现的参数设置
cachedThreadPool fixedThreadPool singleThreadPool scheduledThreadPool corePoolSize 0 指定的大小 1 指定的大小 maxPoolSize Integer.Max 同corePoolSize 1 无实际意思(目前) keepAliveTime 60秒 无实际意义 无实际意义 0