Java Reference
In-Depth Information
Listing 6-18.
A Non-Daemon Thread Example
// NonDaemonThread.java
package com.jdojo.threads;
public class NonDaemonThread {
public static void main(String[] args) {
Thread t = new Thread(NonDaemonThread::print);
// t is already a non-daemon thread because the "main" thread that runs
// the main() method is a non-daemon thread. You can verify it by using
// t.isDaemon() method. It will return false.
// Still we will use the following statement to make it clear that we
// want t to be a non-daemon thread.
t.setDaemon(false);
t.start();
System.out.println("Exiting main method");
}
public static void print() {
int counter = 1;
while(true) {
try {
System.out.println("Counter:" + counter++);
Thread.sleep(2000); // sleep for 2 seconds
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
Exiting main method
Counter:1
Counter:2
...
Am I Interrupted?
You can interrupt a thread that is alive by using the
interrupt()
method. This method invocation on a thread is just
an indication to the thread that some other part of the program is trying to draw its attention. It is up to the thread how
it responds to the interruption. Java implements the interruption mechanism using an
interrupted
status flag for
every thread.
A thread could be in one of the two states when it is interrupted: running or blocked. If a thread is interrupted
when it is running, its
interrupted
status is set by the JVM. The running thread can check its
interrupted
status by
calling the
Thread.interrupted() static
method, which returns
true
if the current thread was interrupted. The
call to the
Thread.interrupted()
method clears the
interrupted
status of a thread. That is, if you call this method
again on the same thread and if the first call returned
true
, the subsequent calls will return
false
, unless the thread is
interrupted after the first call but before the subsequent calls.