java code:
public class test {
public static void main(String[] args) throws InterruptedException {
Customer customer = new Customer();
customer.start(); // start customer
Thread.sleep(5000);
customer.interrupt(); // interrupt
}
}
class Customer extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("test Interrupted +++++");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I call customer.interrupt() but customer is still working;
console result:
test Interrupted +++++
....
test Interrupted +++++
java.lang.InterruptedException: sleep interrupted
test Interrupted +++++
at java.lang.Thread.sleep(Native Method)
at com.yitai.common.redisQueue.Customer.run(test.java:22)
test Interrupted +++++
test Interrupted +++++
.... //more
if i change the code in this way : add Thread.currentThread().interrupt() in catch
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // add this
e.printStackTrace();
}
customer is stoped but why?
console result:
test Interrupted +++++
....
test Interrupted +++++
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.yitai.common.redisQueue.Customer.run(test.java:22)
// the end