forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutors1.java
More file actions
49 lines (44 loc) · 1.4 KB
/
Executors1.java
File metadata and controls
49 lines (44 loc) · 1.4 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Benjamin Winterberg
*/
public class Executors1 {
public static void main(String[] args) {
test1(3);
// test1(7);
}
private static void test1(long seconds) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(seconds);
String name = Thread.currentThread().getName();
System.out.println("task finished: " + name);
}
catch (InterruptedException e) {
System.err.println("task interrupted");
}
});
stop(executor);
}
static void stop(ExecutorService executor) {
try {
System.out.println("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.err.println("termination interrupted");
}
finally {
if (!executor.isTerminated()) {
System.err.println("killing non-finished tasks");
}
executor.shutdownNow();
System.out.println("shutdown finished");
}
}
}