1.可创建线程池种类
在java.util.concurrent中提供了工具类Executors(调度器)对象来创建线程池,有四种
- CachedThreadPool - 可缓存线程池
- 无限大、无线程创建线程,有空闲线程利用起来
- FixedThreadPool - 定长线程池
- 固定线程总数,空闲线程用于执行任务,无空闲线程任务等待
- SingleThreadExecutor - 单线程池
- ScheduledThreadPool - 调度线程池
2.线程池的使用
2.1可缓存线程池
ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 1000; i++) { final int index = i; executorService.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"--"+index); } }); } executorService.shutdown();
2.2定长线程池
ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 1000; i++) { final int index = i; executorService.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"--"+index); } }); } //关闭线程池,等待所有任务执行完毕 executorService.shutdown(); //不等待线程池中的任务执行完毕,直接关闭线程池,不推荐使用 // executorService.shutdownNow();
2.3单线程池
ExecutorService executorService = Executors.newSingleThreadExecutor(); for (int i = 0; i < 1000; i++) { final int index = i; executorService.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"--"+index); } }); } //关闭线程池,等待所有任务执行完毕 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } executorService.shutdown();
2.4调度线程池
执行单次
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5); //换执行方法,不在是execute,而是schedule scheduledExecutorService.schedule(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"-----"+"延迟3秒执行"); } }, 3,java.util.concurrent.TimeUnit.SECONDS); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } scheduledExecutorService.shutdown();
循环执行
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5); //换执行方法,不在是execute,而是schedule System.out.println("当前时间:"+new Date()); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"-----"+new Date()+"--------"+"延迟1秒执行,每3秒执行一次"); } }, 1,3, TimeUnit.SECONDS); //大于1s结束才能执行 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } scheduledExecutorService.shutdown();
标签:Thread,Executors,并发,线程,scheduledExecutorService,new,executorService From: https://www.cnblogs.com/blanset/p/16784068.html