When thread gets terminated (Thread.State.TERMINATED) it is still not interrupted. Why?
I found this, and I found this, but neither answers my question.I have tried this out on OpenJDK 11 and Oracle JDK 16 - no difference, same result.
I have been working with Java for more than 10 years now, and multithreading tasks have always been clear to me; yet, accidentally, I've encountered something strange (to me), which I'm wondering about.
I understand, that private volatile boolean interrupted; is just a flag (field) of class Thread, which I could make use in conjunction with interrupt() in order to code some logic up with the case when isInterrupted() gets true.
However, why does Thread.State.TERMINATED state doesn't also make the same thread interrupted?
public class MainClass {
public static void main(String[] args) throws Exception {
Thread alfa = new Thread(() -> {
for (int i = 0; i < 3; i++) {
System.out.println(i + ". " + Thread.currentThread().getName() + " state: " + Thread.currentThread().getState().name());
try {Thread.sleep(1000);} catch (Exception e) {}
}
});
alfa.setName("Alfa thread");
System.out.println(alfa.getName() + " state before invoking .start() is: " + alfa.getState().name());
alfa.start();
int i = 0;
while (true) {
++i;
System.out.println(i + ". " + alfa.getName() + " state: " + alfa.getState().name());
System.out.println(i + ". " + alfa.getName() + " is interrupted?: " + alfa.isInterrupted());
Thread.sleep(1000);
}
}
}
demonstrates, this:
Alfa thread state before invoking .start() is: NEW
1. Alfa thread state: RUNNABLE
0. Alfa thread state: RUNNABLE
1. Alfa thread is interrupted?: false
1. Alfa thread state: RUNNABLE
2. Alfa thread state: TIMED_WAITING
2. Alfa thread is interrupted?: false
2. Alfa thread state: RUNNABLE
3. Alfa thread state: TIMED_WAITING
3. Alfa thread is interrupted?: false
4. Alfa thread state: TERMINATED //alfa is terminated!
4. Alfa thread is interrupted?: false //alfa is not interrupted. Seriously?
- Am I not getting something and this is purposefully done so, as it has some idea behind the scenes? or
- It is just something, that has been forgotten to be implemented correctly?