I try to consider with multithreading and with interrupt() method:
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().isInterrupted());
Runnable target = new Runnable() {
@Override
public void run() {
try {
System.out.println("From thread-run(): " + Thread.currentThread().isInterrupted());
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("From thread-catch(): " + Thread.currentThread().isInterrupted());
}
}
};
Thread someThread = new Thread(target);
System.out.println("Before start(): " + someThread.isInterrupted());
someThread.start();
Thread.sleep(1000);
System.out.println("After start(): " + someThread.isInterrupted());
someThread.interrupt();
Thread.sleep(1000);
System.out.println("After interrupt: " + someThread.isInterrupted());
}
As I understood, the interrupt()
method set flag interrupt
to true
. In this case, the thread supposed to be stopped immediately, but my code return false
in all cases:
I changed my method in the way when the thread interrupt himself:
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().isInterrupted());
Runnable target = new Runnable() {
@Override
public void run() {
System.out.println("From thread-run(): " + Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
}
};
Thread someThread = new Thread(target);
System.out.println("Before start(): " + someThread.isInterrupted());
someThread.start();
Thread.sleep(1000);
System.out.println("After start(): " + someThread.isInterrupted());
Thread.sleep(1000);
System.out.println("After interrupt: " + someThread.isInterrupted());
}
But the result is the same:
I supposed, the From thread-catch():
and After interrupt:
lines should have returned true instead of false - why isInterrupted() == false if the thread was interrupted?
the answer from Why do InterruptedExceptions clear a thread's interrupted status? do not acceptable for my case since in the second case the InterruptException
do not happen and
- a) not "would have to explicitly clear that flag":
- b) I used
Thread.currentThread().interrupt()
- anyway I gotfalse
- c) The
interrupt()
was handled once