Java Reference
In-Depth Information
Listing 6-19 shows the code that interrupts the main thread and prints the interrupted status of the thread.
Note that the second call to the Thread.interrupted() method returns false , as indicated in the output #3:false .
This example also shows that a thread can interrupt itself. The main thread that is responsible for running the main()
method is interrupting itself in this example.
Listing 6-19. A Simple Example of Interrupting a Thread
// SimpleInterrupt.java
package com.jdojo.threads;
public class SimpleInterrupt {
public static void main(String[] args) {
System.out.println("#1:" + Thread.interrupted());
// Now interrupt the main thread
Thread.currentThread().interrupt();
// Check if it has been interrupted
System.out.println("#2:" + Thread.interrupted());
// Check again if it has been interrupted
System.out.println("#3:" + Thread.interrupted());
}
}
#1:false
#2:true
#3:false
Let's have another example of the same kind. This time, one thread will interrupt another thread. Listing 6-20
starts a thread that increments a counter until the thread is interrupted. At the end, the thread prints the value of the
counter. The main() method starts the thread; it sleeps for one second to let the counter thread do some work;
it interrupts the thread. Since the thread checks whether it has been interrupted or not before continuing in the
while-loop, it exits the loop once it is interrupted. You may a different output when you run this program.
Listing 6-20. A Thread Interrupting Another Thread
// SimpleInterruptAnotherThread.java
package com.jdojo.threads;
public class SimpleInterruptAnotherThread {
public static void main(String[] args) {
Thread t = new Thread(SimpleInterruptAnotherThread::run);
t.start();
// Let the main thread sleep for 1 second
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
Search WWH ::




Custom Search