1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 import java.util.concurrent.TimeUnit; 4 5 /** 6 * java5线程并发库的应用 7 * 线程池工具类 Executors 8 * 9 * @author LiTaiQing 10 * 11 */ 12 public class ThreadPoolTest { 13 14 public static void main(String[] args) { 15 //固定大小的线程池 16 //ExecutorService threadPool = Executors.newFixedThreadPool(3); 17 //缓存线程池 18 //ExecutorService threadPool = Executors.newCachedThreadPool(); 19 /** 20 * 单一线程池(如何实现线程死掉后重新启动) 21 * 此线程池的特点正好解决上述问题,如果线程挂掉,此线程池会自动创建一个线程代替挂掉的线程 22 */ 23 ExecutorService threadPool = Executors.newSingleThreadExecutor(); 24 for (int i = 1; i < 10; i++) { 25 final int task = i; 26 threadPool.execute(new Runnable() { 27 @Override 28 public void run() { 29 for (int j = 0; j < 10; j++) { 30 try { 31 Thread.sleep(20); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 System.out.println(Thread.currentThread().getName() 36 + " is looping of " + j 37 + " for task of " + task); 38 } 39 } 40 }); 41 } 42 System.out.println("all of 10 tasks have committed!"); 43 //当所有任务结束后关闭线程池 44 //threadPool.shutdown(); 45 //不管所有任务是否都已结束,直接关闭线程池 46 //threadPool.shutdownNow(); 47 //计时器 48 // Executors.newScheduledThreadPool(3).schedule(new Runnable(){ 49 // @Override 50 // public void run() { 51 // System.out.println("bombing!"); 52 // } 53 // }, 54 // 6, //时间 55 // TimeUnit.SECONDS);//单位 56 57 /** 58 * 固定频率 59 * 实现6秒以后炸,以后每2秒后爆炸一次 60 */ 61 Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable(){ 62 @Override 63 public void run() { 64 System.out.println("bombing!"); 65 } 66 }, 67 6, //时间 68 2, //时间间隔 69 TimeUnit.SECONDS);//单位 70 } 71 72 73 }
时间: 2024-10-15 20:01:59