高级并发学习之 各种线程池的使用

来源:互联网 发布:php将文件夹压缩成zip 编辑:程序博客网 时间:2024/06/07 00:53
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;public class ThreadPoolTest {public static void main(String[] args) throws InterruptedException, ParseException {//创建固定大小的线程池,通过共享无界队列的方式来运行这些线程新加的任务超过了线程池的大小 则存放在工作队列中//ExecutorService threadPool=Executors.newFixedThreadPool(3);//创建缓存线程池 如果当前线程没有可用的,则创建一个新的线程并添加到池中;长时间的空闲线程使用每隔60s清除一次//ExecutorService threadPool=Executors.newCachedThreadPool();//创建单一线程(可以实现线程死掉后重新启动,实际是找到一个替补)ExecutorService threadPool=Executors.newSingleThreadExecutor();for(int j=0;j<10;j++){final int task=j;threadPool.execute(new Runnable(){@Overridepublic void run() {for(int i=0;i<10;i++){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+"正在执行第 "+task+"个任务的第"+i+"次循环");}}});}threadPool.shutdown();while(!threadPool.awaitTermination(1, TimeUnit.SECONDS)){}System.out.println("所有任务都结束");//创建定时任务线程池Executors.newScheduledThreadPool(3).schedule(new Runnable(){@Overridepublic void run() {//需要进行处理的任务System.out.println("bombing");}}, 5, TimeUnit.SECONDS);//创建含有定时器的线程池任务Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){@Overridepublic void run() {System.out.println("爆炸....");}}, 6, 2, TimeUnit.SECONDS);//延迟6s后每隔2s爆炸一次/***********************如果要求在特定的某一日期的某一时刻执行,则应该使用以下方法***************************/SimpleDateFormat CUSTOM_DAYTIME_FORMATOR = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date=CUSTOM_DAYTIME_FORMATOR.parse("2016-01-11 15:37:00");Executors.newScheduledThreadPool(3).schedule(new Runnable(){@Overridepublic void run() {//需要进行处理的任务System.out.println("定时bombing");}}, 5, TimeUnit.SECONDS); System.out.println((date.getTime()-System.currentTimeMillis())/1000/60);}}

0 0