OnJava8-Examples/concurrent/SingleThreadExecutor.java

50 lines
1.3 KiB
Java
Raw Normal View History

2016-11-23 09:05:26 -08:00
// concurrent/SingleThreadExecutor.java
2020-10-07 13:35:40 -06:00
// (c)2020 MindView LLC: see Copyright.txt
2016-07-05 14:46:09 -06:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-07-05 14:46:09 -06:00
import java.util.concurrent.*;
2016-12-21 11:06:49 -08:00
import java.util.stream.*;
import onjava.*;
2016-07-05 14:46:09 -06:00
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService exec =
Executors.newSingleThreadExecutor();
2016-12-21 11:06:49 -08:00
IntStream.range(0, 10)
.mapToObj(NapTask::new)
.forEach(exec::execute);
2016-07-05 14:46:09 -06:00
System.out.println("All tasks submitted");
exec.shutdown();
while(!exec.isTerminated()) {
System.out.println(
Thread.currentThread().getName() +
" awaiting termination");
2017-01-22 16:48:11 -08:00
new Nap(0.1);
2016-07-05 14:46:09 -06:00
}
}
}
/* Output:
All tasks submitted
main awaiting termination
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[0] pool-1-thread-1
2016-07-05 14:46:09 -06:00
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[1] pool-1-thread-1
2016-07-22 14:45:35 -06:00
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[2] pool-1-thread-1
2016-07-05 14:46:09 -06:00
main awaiting termination
NapTask[3] pool-1-thread-1
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[4] pool-1-thread-1
2016-07-05 14:46:09 -06:00
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[5] pool-1-thread-1
2016-07-05 14:46:09 -06:00
main awaiting termination
NapTask[6] pool-1-thread-1
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[7] pool-1-thread-1
2016-07-05 14:46:09 -06:00
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[8] pool-1-thread-1
2016-07-22 14:45:35 -06:00
main awaiting termination
2016-12-21 11:06:49 -08:00
NapTask[9] pool-1-thread-1
2016-07-05 14:46:09 -06:00
*/