1 package com.thread.test.thread; 2 import java.util.Timer; 3 import java.util.TimerTask; 4 import java.util.concurrent.*; 5 import java.util.concurrent.locks.ReentrantLock; 6 7 /** 8 * schedule(Runnable command, long delay, TimeUnit unit) 9 * @ command: 需要執行的任務 10 * @ delay:任務執行需要延遲的時間 11 * @ unit:時間單位 12 * 13 * 一次性執行任務,執行完成結束 14 * 15 * ScheduledExecutorService: 16 * scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 17 * @ Runnable command: 需要執行的任務 18 * @ long initialDelay:第一次執行延遲的時間 19 * @ long period:間隔周期 20 * @ TimeUnit unit 21 * 22 * 包含首次延遲的周期性執行任務,第一次執行:delay+period,第二次:delay+2*period,以此類推... 23 * 停止:異常停止執行,主動調用停止方法 24 * 如果某一個周期執行時間超過設定的period,則后續順延 25 * 26 * scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 27 * @ command: 需要執行的任務 28 * @ initialDelay:第一次執行延遲的時間 29 * @ delay:周期之間的延遲,間隔 30 * @ unit:前兩個參數的單位 31 * 32 * 周期性執行任務:第一次執行:initialDelay+delay,第二次:initialDelay+2*delay,以此類推... 33 * 停止:異常停止執行,主動調用停止方法 34 * 不順延 35 * 36 * Created by windwant on 2016/5/26. 37 */ 38 public class MyExecutor { 39 public static void main(String[] args) { 40 testTimer(); 41 } 42 43 public static void testTimer(){ 44 new Timer().schedule(new MyTimerTask(), 2000, 5000); 45 } 46 47 public static void testExecutors(){ 48 MyERunnable mer = new MyERunnable(5); 49 // ExecutorService es = Executors.newCachedThreadPool(); 50 // ExecutorService es = Executors.newFixedThreadPool(2); 51 ScheduledExecutorService es = Executors.newScheduledThreadPool(2); 52 es.schedule(mer, 10000, TimeUnit.SECONDS.MILLISECONDS); 53 es.scheduleAtFixedRate(mer, 2, 10, TimeUnit.SECONDS); 54 es.scheduleWithFixedDelay(mer, 1, 5, TimeUnit.SECONDS); 55 es.shutdown(); 56 } 57 } 58 59 class MyERunnable implements Runnable{ 60 private int num = 0; 61 MyERunnable(int num){ 62 this.num = num; 63 } 64 public void run() { 65 ReentrantLock lock = new ReentrantLock(); 66 try{ 67 lock.lock(); 68 for (int i = 0; i < num; i++) { 69 System.out.println("current thread: " + Thread.currentThread().getName() + " num--" + i); 70 Thread.sleep(1000); 71 } 72 }catch (Exception e){ 73 e.printStackTrace(); 74 }finally { 75 lock.unlock(); 76 } 77 } 78 } 79 80 class MyTimerTask extends TimerTask{ 81 82 @Override 83 public void run() { 84 System.out.println("timer task"); 85 } 86 }
項目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo
