Senior
How can a thread indicate that it can be interrupted so that another thread can execute?
sobes.tech AI
Answer from AI
In Java, a thread can indicate that it can be interrupted using the interruption mechanism. This is done by calling the interrupt() method on the thread object. Inside the thread, it should periodically check the interruption flag using the Thread.interrupted() or isInterrupted() methods. If the thread detects that it has been interrupted, it can properly finish its work, release resources, and exit.
Example:
public class MyRunnable implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// Perform work
try {
Thread.sleep(1000); // may throw InterruptedException
} catch (InterruptedException e) {
// Thread was interrupted during sleep
Thread.currentThread().interrupt(); // restore interruption flag
break; // exit loop
}
}
System.out.println("Thread finished");
}
}
// Elsewhere:
Thread thread = new Thread(new MyRunnable());
thread.start();
// ...
thread.interrupt(); // interruption signal
Thus, the thread controls its termination by reacting to the interruption.