0

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
andy.hu
  • 325
  • 1
  • 2
  • 10

1 Answers1

0

What is happening is that calling Thread.interrupt() clears the thread's interrupted status if the thread is currently waiting, causing your loop to continue. From the Javadoc (my emphasis):

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

To put it another way, if it is currently possible for the thread to receive an InterruptedException (because it is in a wait state) then it the exception will be sent and the interrupt status is cleared. The interrupt status is set only when it is not possible to synchronously deliver the exception.

You need to account for that in your program's logic for terminating the thread, assuming that is your intention. You need to correctly handle both possibilities.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190