OnJava8-Examples/tasks/DaemonFromFactory.java

45 lines
1.5 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// tasks/DaemonFromFactory.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Using a Thread Factory to create daemons
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import onjava.*;
2015-06-15 17:47:35 -07:00
public class DaemonFromFactory implements Runnable {
@Override
public void run() {
try {
while(true) {
TimeUnit.MILLISECONDS.sleep(100);
2015-12-02 09:20:27 -08:00
System.out.println(
Thread.currentThread() + " " + this);
2015-06-15 17:47:35 -07:00
}
} catch(InterruptedException e) {
2015-11-03 12:00:44 -08:00
System.out.println("Interrupted");
2015-06-15 17:47:35 -07:00
}
}
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
ExecutorService exec = Executors.newCachedThreadPool(
new DaemonThreadFactory());
for(int i = 0; i < 10; i++)
exec.execute(new DaemonFromFactory());
2015-11-03 12:00:44 -08:00
System.out.println("All daemons started");
2015-06-15 17:47:35 -07:00
TimeUnit.MILLISECONDS.sleep(500); // Run for a while
}
2015-09-07 11:44:36 -06:00
}
/* Output: (First 10 Lines)
2015-06-15 17:47:35 -07:00
All daemons started
2015-11-03 12:00:44 -08:00
Thread[Thread-2,5,main] DaemonFromFactory@1bb3d5e
Thread[Thread-8,5,main] DaemonFromFactory@12aef8a
Thread[Thread-9,5,main] DaemonFromFactory@b5ecf4
Thread[Thread-0,5,main] DaemonFromFactory@3e3d06
Thread[Thread-1,5,main] DaemonFromFactory@425a41
Thread[Thread-5,5,main] DaemonFromFactory@4f61c0
Thread[Thread-4,5,main] DaemonFromFactory@53f1ba
Thread[Thread-6,5,main] DaemonFromFactory@baf372
Thread[Thread-3,5,main] DaemonFromFactory@1437b8f
2015-06-15 17:47:35 -07:00
...
2015-09-07 11:44:36 -06:00
*/