Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i understand Thread.interrupt()?
    text
    copied!<p>There are two code block in java.</p> <p>Block One:</p> <pre><code>@Test public void test1() { System.out.println("interrupt:" + Thread.currentThread().isInterrupted()); Thread.currentThread().interrupt(); System.out.println("interrupt:" + Thread.currentThread().isInterrupted()); } </code></pre> <p>Output:</p> <pre><code>interrupt:false interrupt:true </code></pre> <p>Block Two:</p> <pre><code>@Test public void test2() throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("running..."); } }); thread.interrupt(); TimeUnit.SECONDS.sleep(2); System.out.println("interrupt:" + thread.isInterrupted()); thread.start(); TimeUnit.SECONDS.sleep(2); System.out.println("interrupt:" + thread.isInterrupted()); } </code></pre> <p>Output:</p> <pre><code>interrupt:false running... interrupt:false </code></pre> <p>So, my questions:</p> <ol> <li>Why block one print <code>interrupt:true</code> after invoke <code>interrupt()</code> but block two not?</li> <li>What will JVM do after invoke interrupt()?</li> </ol> <p>Thanks!</p> <p>PS:Block Three:</p> <pre><code>@Test public void test3() { Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("running..."); } }); thread.interrupt(); System.out.println("interrupt:" + thread.isInterrupted()); // thread.start(); // // thread.interrupt(); // // // System.out.println("interrupt:" + thread.isInterrupted()); } </code></pre> <p>Also output : <code>interrupt:false</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload