Skip to content

Instantly share code, notes, and snippets.

@john77eipe
Created September 25, 2016 19:24
Show Gist options
  • Save john77eipe/0b5bc09cb5accedadddc5b92ef99b3a7 to your computer and use it in GitHub Desktop.
Save john77eipe/0b5bc09cb5accedadddc5b92ef99b3a7 to your computer and use it in GitHub Desktop.
Daemon and User threads
package testex;
/**
* Notice the difference between daemon (background) threads and non-daemon (user) threads
* - Finally blocks are not executed for daemon threads
* - JVM is concerned about user threads only
* - JVM exits when all user threads are completed in other words JVM waits for user threads to run to completion
* - JVM doesn't wait for daemon threads - simply kills it when JVM is ready to exit (or killed by user action)
* - If any clean up needs to be done for daemon threads (works for user threads also) put them as a shutdown hook
* @author johne
*
*/
public class TestThreads {
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName() +" starting");
MyThread t1 = new MyThread();
t1.setDaemon(true);
t1.setName("Daemon thread");
MyThread t2 = new MyThread();
t2.setName("User thread");
t1.start();
t2.start();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() +" exiting");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Shutdown hook called");
}
});
}
}
class MyThread extends Thread {
@Override
public void run() {
try {
int i=1;
while (i<=5) {
if (Thread.currentThread().isDaemon()) {
System.out.println("i="+ i + " ... "
+ Thread.currentThread().getName());
Thread.sleep(2000);
} else {
System.out.println("i="+ i + " ... "
+ Thread.currentThread().getName());
Thread.sleep(1000);
}
i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Thread exiting ... "
+ Thread.currentThread().getName()); // never called
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment