Explore Connect Documentation
Snippets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
  public static void main(String args[]) throws Exception {
    final ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);
    final long startTime = System.nanoTime();
    
    for (int i = 0; i < 3; i++) {
      final int id = i;
      
      threadPool.scheduleAtFixedRate(() ->
        doWork(id, startTime), 0, 100, TimeUnit.MILLISECONDS);
    }
    threadPool.schedule(threadPool::shutdown, 300, TimeUnit.MILLISECONDS);
    
    if (threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
      System.out.println("Thread pool terminated gracefully.");
    } else {
      System.err.println("Thread pool timed out!");
    }
  }
  
  private static void doWork(final int id, final long start) {
    System.out.println("ID: " + id + "\tTimestamp: " + (System.nanoTime() - start));
  }
}
Press desired key combination and then press ENTER.