-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutorDemo.java
More file actions
47 lines (40 loc) · 1.47 KB
/
ExecutorDemo.java
File metadata and controls
47 lines (40 loc) · 1.47 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
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecutorDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
executor.submit(() ->
{
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
}
//java process never stops! Executors have to be stopped explicitly
//- otherwise they keep listening for new tasks
// shutdown means the executor service takes no more incoming tasks.
// awaitTermination is invoked after a shutdown request.
// You need to first shut down the service and
// then block and wait for threads to finish.
try {
System.out.println("attempt to shutdown executor");
//shutdown doesn't force stop running task but reject new tasks
executor.shutdown();
//Blocks until all tasks have completed execution after a shutdown request
//return true if this executor terminated
//and false if the timeout elapsed before termination
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.err.println("tasks interrupted");
}
finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
executor.shutdownNow();
}
System.out.println("shutdown finished");
}
}
}