Я тестирую InterruptedException со следующим тестовым кодом:
Runnable runMe = new Runnable() {
@Override
public void run() {
for(int i=0; i<6; i++) {
System.out.println("i = "+i);
if(i==3) {
System.out.println("i==3, Thread = "
+Thread.currentThread().getId());
//I invoke interrupt() on the working thread.
Thread.currentThread().interrupt();
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
//I caught InterruptedException
System.out.println(Thread.currentThread().getId()
+ " is interrupted!");
Thread.currentThread().interrupt();
}
}
}
}
};
Thread workingThread = new Thread(runMe);
workingThread.start();
try {
workingThread.join();
} catch (InterruptedException e) {
//Swallow
}
//the following log shows me workingThread.isInterrupted() is false, why?
System.out.println("workingThread("
+ workingThread.getId()+") interrupted ? "
+ workingThread.isInterrupted());
В run()
я interrupt()
текущий рабочий поток и поймал InterruptedException
.
В основном потоке моя последняя строка кода — это System.out.println(...)
, которая выводит статус прерывания рабочего потока. Поскольку я поймал InterruptedException
в run()
, я должен был получить сообщение о том, что workingThread.isInterrupted()
истина, но я получил ложь, почему?
sleep
здесь. Вы намекаете на то, что что-то в их примере сбрасывает флаг прерывания? - person Sotirios Delimanolis   schedule 17.10.2014