在 ScheduledExecutorService 上折腾了半天,先记下来。后面再补充其他线程池。
1
2
3
ScheduledExecutorService
先是想当然地用了这个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public void testSchedule() { ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); System.out.println("start");
executorService.schedule(() -> { System.out.println("1"); }, 2, TimeUnit.SECONDS);
try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("finish"); }
|
但是打印结果是:
1 2 3 4 5
| start 1 finish
Process finished with exit code 0
|
只执行了一次,线程就结束了。这显然不是我想要的。想了一下,喔,schedule
只是一个定时执行,当然不会循环了……
然后点进去类里面,看到了这个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public void testScheduleAtFixedRate() { ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); System.out.println("start");
executorService.scheduleAtFixedRate(() -> { System.out.println("1"); }, 2, 2, TimeUnit.SECONDS);
try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("finish"); }
|
打印结果是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| start 1 1 1 1 1 1 1 1 1 finish 1
Process finished with exit code 0
|
先这么用着吧。