Java Reference
In-Depth Information
#1:false
#2:true
#3:true
#4:true
#5:false
You may interrupt a blocked thread. Recall that a thread may block itself by executing one of the sleep() ,
wait() , and join() methods. If a thread blocked on these three methods is interrupted, an InterruptedException
is thrown and the interrupted status of the thread is cleared because the thread has already received an exception
to signal the interruption.
Listing 6-22 starts a thread that sleeps for one second and prints a message until it is interrupted. The main
thread sleeps for five seconds, so the sleeping thread gets a chance to sleep and print messages a few times.
When the main thread wakes up, it interrupts the sleeping thread. You may get a different output when you run
the program.
Listing 6-22. Interrupting a Blocked Thread
// BlockedInterrupted.java
package com.jdojo.threads;
public class BlockedInterrupted {
public static void main(String[] args) {
Thread t = new Thread(BlockedInterrupted::run);
t.start();
// main thread sleeps for 5 seconds
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// Interrupt the sleeping thread
t.interrupt();
}
public static void run() {
int counter = 1;
while (true) {
try {
Thread.sleep(1000);
System.out.println("Counter:" + counter++);
}
catch (InterruptedException e) {
System.out.println("I got interrupted!");
Search WWH ::




Custom Search