1)创建固定大小线程池
- public class ThreadTest {
- public static void main(String[] args) {
- //ExecutorService executorService = Executors.newFixedThreadPool(2); //创建一个可重用固定线程数的线程池
- //ExecutorService executorService = Executors.newSingleThreadExecutor(); //创建单任务线程池
- ExecutorService executorService = Executors.newCachedThreadPool(); //创建一个可变尺寸的线程池
- Task task1 = new Task();
- Task task2 = new Task();
- Task task3 = new Task();
- executorService.execute(task1);
- executorService.execute(task2);
- executorService.execute(task3);
- executorService.shutdown();
- }
- }
- class Task implements Runnable {
- public void run() {
- System.out.println(Thread.currentThread().getName() + " Hello");
- }
- }
对于大小固定的线程池,如:newFixedThreadPool(int size)和newSingeThreadExecutor(),当要加入的任务大于线程池的大小时,则任务需要排队等待。
2)创建可变尺寸线程池
- public class ThreadTest {
- public static void main(String[] args) {
- ExecutorService executorService = Executors.newCachedThreadPool(); //创建一个可变尺寸的线程池
- Task task1 = new Task();
- Task task2 = new Task();
- Task task3 = new Task();
- executorService.execute(task1);
- executorService.execute(task2);
- executorService.execute(task3);
- executorService.shutdown();
- }
- }
- class Task implements Runnable {
- public void run() {
- System.out.println(Thread.currentThread().getName() + " Hello");
- }
- }
3)创建延迟连接线程池
- public class ThreadTest {
- public static void main(String[] args) {
- ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
- Task task1 = new Task();
- Task task2 = new Task();
- Task task3 = new Task();
- executorService.execute(task1);
- executorService.scheduleAtFixedRate(task2,0L,2,TimeUnit.HOURS); //此方法表示在指定的周期内循环执行task2任务,2表示循环的周期,TimeUtils.HOURS表示循 环周期的时间单位,此处是小时
- executorService.schedule(task3,10, TimeUnit.HOURS); //task2是实现Runnable接口的任务,10时延迟的时间,TimeUtil.HOURS是延迟时间的计量单位,在此处是小 时
- executorService.shutdown();
- }
- }
- class Task implements Runnable {
- public void run() {
- System.out.println(Thread.currentThread().getName() + " Hello");
- }
- }