|
16 | 16 | public class Executors3 { |
17 | 17 |
|
18 | 18 | public static void main(String[] args) throws InterruptedException, ExecutionException { |
19 | | -// test1(); |
| 19 | + test1(); |
20 | 20 | // test2(); |
21 | 21 | // test3(); |
22 | 22 |
|
23 | 23 | // test4(); |
24 | | - test5(); |
| 24 | +// test5(); |
25 | 25 | } |
26 | 26 |
|
27 | 27 | private static void test5() throws InterruptedException, ExecutionException { |
@@ -70,26 +70,37 @@ private static void test4() throws InterruptedException { |
70 | 70 |
|
71 | 71 | private static void test3() { |
72 | 72 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); |
73 | | - executor.scheduleWithFixedDelay(() -> { |
| 73 | + |
| 74 | + Runnable task = () -> { |
74 | 75 | try { |
75 | 76 | TimeUnit.SECONDS.sleep(2); |
76 | 77 | System.out.println("Scheduling: " + System.nanoTime()); |
77 | 78 | } |
78 | 79 | catch (InterruptedException e) { |
79 | 80 | System.err.println("task interrupted"); |
80 | 81 | } |
81 | | - }, 0, 1, TimeUnit.SECONDS); |
| 82 | + }; |
| 83 | + |
| 84 | + executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); |
82 | 85 | } |
83 | 86 |
|
84 | 87 | private static void test2() { |
85 | 88 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); |
86 | | - executor.scheduleAtFixedRate(() -> System.out.println("Scheduling: " + System.nanoTime()), 0, 1, TimeUnit.SECONDS); |
| 89 | + Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime()); |
| 90 | + int initialDelay = 0; |
| 91 | + int period = 1; |
| 92 | + executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS); |
87 | 93 | } |
88 | 94 |
|
89 | 95 | private static void test1() throws InterruptedException { |
90 | 96 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); |
91 | | - ScheduledFuture<?> future = executor.schedule(() -> System.out.println("Scheduling: " + System.nanoTime()), 3, TimeUnit.SECONDS); |
| 97 | + |
| 98 | + Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime()); |
| 99 | + int delay = 3; |
| 100 | + ScheduledFuture<?> future = executor.schedule(task, delay, TimeUnit.SECONDS); |
| 101 | + |
92 | 102 | TimeUnit.MILLISECONDS.sleep(1337); |
| 103 | + |
93 | 104 | long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS); |
94 | 105 | System.out.printf("Remaining Delay: %sms\n", remainingDelay); |
95 | 106 | } |
|
0 commit comments