Java Reference
In-Depth Information
// Now interrupt the thread
t.interrupt();
}
public static void run() {
int counter = 0;
while (!Thread.interrupted()) {
counter++;
}
System.out.println("Counter:" + counter);
}
}
Counter:1630140
The Thread class has a non-static isInterrupted() method that can be used to test if a thread has been
interrupted. When you call this method, unlike the interrupted() method, the interrupted status of the
thread is not cleared. Listing 6-21 demonstrates the difference between the two methods: interrupted() and
isInterrupted() .
Listing 6-21. Difference Between the interrupted() and isInterrupted() Methods
// SimpleIsInterrupted.java
package com.jdojo.threads;
public class SimpleIsInterrupted {
public static void main(String[] args) {
// Check if the main thread is interrupted
System.out.println("#1:" + Thread.interrupted());
// Now interrupt the main thread
Thread mainThread = Thread.currentThread();
mainThread.interrupt();
// Check if it has been interrupted
System.out.println("#2:" + mainThread.isInterrupted());
// Check if it has been interrupted
System.out.println("#3:" + mainThread.isInterrupted());
// Now check if it has been interrupted using the static method
// which will clear the interrupted status
System.out.println("#4:" + Thread.interrupted());
// Now, isInterrupted() should return false, because previous
// statement Thread.interrupted() has cleared the flag
System.out.println("#5:" + mainThread.isInterrupted());
}
}
Search WWH ::




Custom Search