本人郵箱: <kco1989@qq.com>
歡迎轉載,轉載請註明網址 http://blog.csdn.net/tianshi_kco
github: https://github.com/kco1989/kco
代碼已經所有託管github有須要的同窗自行下載java
java 提供的線程池還有一個,那就是任務調度線程池ScheduledThreadPoolExecutor
,它實際上是ThreadPoolExecutor
的一個子類.git
咱們經過查看ScheduledThreadPoolExecutor
的源代碼,能夠發現ScheduledThreadPoolExecutor
的構造器都是調用父類的構造器,只是它使用的工做隊列是java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue
經過名字咱們均可以猜到這個是一個延時工做隊列.
由於ScheduledThreadPoolExecutor
的最大線程是Integer.MAX_VALUE,並且根據源碼能夠看到execute
和submit
其實都是調用schedule
這個方法,並且延時時間都是指定爲0,因此調用execute
和submit
的任務都直接被執行.github
咱們搞幾個延時炸彈,讓它們每一個5s炸一次微信
public class TestMain { public static void main(String[] args) throws InterruptedException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(5); for (int i = 0; i < 5; i ++){ final int temp = i + 1; pool.schedule(() -> { System.out.println("第"+temp+"個炸彈爆炸時間:" + simpleDateFormat.format(new Date())); }, temp * 5, TimeUnit.SECONDS); } pool.shutdown(); System.out.println("end main時間:" + simpleDateFormat.format(new Date())); } }
運行結果:spa
end main時間:2016-11-03 19:58:31
第1個炸彈爆炸時間:2016-11-03 19:58:36
第2個炸彈爆炸時間:2016-11-03 19:58:41
第3個炸彈爆炸時間:2016-11-03 19:58:46
第4個炸彈爆炸時間:2016-11-03 19:58:51
第5個炸彈爆炸時間:2016-11-03 19:58:56.net
ok,這個類相對比較簡單,我就很少講了線程
在正在項目中,通常若是須要使用定時任務,不會直接使用這個類的.有一個quartz
已經把定時任務封裝的很好了.它是經過cron
表示時,能夠指定某一個任務天天執行,或者每週三下午5點執行.更多的資料能夠去查百度.或者等之後有機會我再整理一寫經常使用jar用法系列文章.就這樣了.code
若是以爲個人文章寫的還過得去的話,有錢就捧個錢場,沒錢給我捧我的場(幫我點贊或推薦一下)
orm