Calling Thread.sleep() with *interrupted status* set?

前端 未结 4 1681
面向向阳花
面向向阳花 2020-12-16 14:16

The Java documentation is not clear on this point. What happens if you call interrupt on a Thread before a call to Thread.sleep():

        //interrup         


        
4条回答
  •  [愿得一人]
    2020-12-16 14:58

    You can use the following class to test the behavior. In this case, the loop is not interrupted and the thread dies when it gets to the sleep.

    public class TestInterrupt{

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(){
            public void run(){
                System.out.println("hello");
                try {
                    for (int i = 0 ; i < 1000000; i++){
                        System.out.print(".");
                    }
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println("interrupted");
                    e.printStackTrace();  
                }
    
            }
        };
        t.start();
        Thread.sleep(100);
        System.out.println("about to interrupt.");
        t.interrupt();
    
    }
    

    }

提交回复
热议问题