1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package com.demo;
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) { System.out.println(Runtime.getRuntime().availableProcessors()); //testSingleThreadExecutor(); //testFixedThreadPool(); //testCachedThreadPool(); }
/** * 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待 */ public static void testFixedThreadPool(){ //因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。 //定长线程池的大小最好根据系统资源进行设置。如获取cpu核心数Runtime.getRuntime().availableProcessors() ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { final int index = i; fixedThreadPool.execute(new Runnable() { public void run() { try { System.out.println(index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } }
/** * 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。 */ public static void testCachedThreadPool(){ ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int index = i; try { Thread.sleep(index * 1000); } catch (InterruptedException e) { e.printStackTrace(); } cachedThreadPool.execute(new Runnable() { public void run() { System.out.println(index); } }); } } /** * 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行 */ public static void testSingleThreadExecutor(){ ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int index = i; singleThreadExecutor.execute(new Runnable() { public void run() { try { System.out.println(index); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } /** * 创建一个定长线程池,支持定时及周期性任务执行 */ public static void testScheduledThreadPool(){ ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(new Runnable() { public void run() { System.out.println("delay 3 seconds"); } //延迟3秒执行 }, 3, TimeUnit.SECONDS); //延迟1秒后每3秒执行一次。 //}, 3, TimeUnit.SECONDS); } }
|