簡體   English   中英

我怎么能理解Thread.interrupt()?

[英]How can i understand Thread.interrupt()?

java中有兩個代碼塊。

第一座:

@Test
public void test1() {

    System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
    Thread.currentThread().interrupt();
    System.out.println("interrupt:" + Thread.currentThread().isInterrupted());

}

輸出:

interrupt:false
interrupt:true

第二塊:

@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());

}

輸出:

interrupt:false
running...
interrupt:false

所以,我的問題:

  1. 為什么要阻止一個打印interrupt:true在調用interrupt()之后為interrupt:true但是不阻止第二個?
  2. 調用interrupt()后JVM會做什么?

謝謝!

PS:第三塊:

@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());

}

還輸出: interrupt:false

  • 在塊1中,你打斷自己,這個“標記”帶有中斷標志的線程。
  • 在塊2中,您中斷其他線程(不活動 - 未啟動 - )

嘗試在run()方法中添加Thread.sleep(5000); 並在中斷前開始;-)

中斷如何工作

這很容易。 由於sleep文件:

InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

當你調用interrupt並且線程處於休眠狀態時,拋出了異常並且它只是清除了interrupted標志。

第三塊:

由於文檔: Interrupting a thread that is not alive need not have any effect. 所以總結一下:如果你的線程還沒有啟動,那么interrupt方法可能無法正常工作。

java.lang.Thread的源代碼中,對於interrupt方法,文檔清楚地說:

中斷不活動的線程不會產生任何影響。

  888       /**
  889        * Interrupts this thread.
  890        *
  891        * <p> Unless the current thread is interrupting itself, which is
  892        * always permitted, the {@link #checkAccess() checkAccess} method
  893        * of this thread is invoked, which may cause a {@link
  894        * SecurityException} to be thrown.
  895        *
  896        * <p> If this thread is blocked in an invocation of the {@link
  897        * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
  898        * Object#wait(long, int) wait(long, int)} methods of the {@link Object}
  899        * class, or of the {@link #join()}, {@link #join(long)}, {@link
  900        * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
  901        * methods of this class, then its interrupt status will be cleared and it
  902        * will receive an {@link InterruptedException}.
  903        *
  904        * <p> If this thread is blocked in an I/O operation upon an {@link
  905        * java.nio.channels.InterruptibleChannel </code>interruptible
  906        * channel<code>} then the channel will be closed, the thread's interrupt
  907        * status will be set, and the thread will receive a {@link
  908        * java.nio.channels.ClosedByInterruptException}.
  909        *
  910        * <p> If this thread is blocked in a {@link java.nio.channels.Selector}
  911        * then the thread's interrupt status will be set and it will return
  912        * immediately from the selection operation, possibly with a non-zero
  913        * value, just as if the selector's {@link
  914        * java.nio.channels.Selector#wakeup wakeup} method were invoked.
  915        *
  916        * <p> If none of the previous conditions hold then this thread's interrupt
  917        * status will be set. </p>
  918        *
  919        * <p> Interrupting a thread that is not alive need not have any effect.
  920        *
  921        * @throws  SecurityException
  922        *          if the current thread cannot modify this thread
  923        *
  924        * @revised 6.0
  925        * @spec JSR-51
  926        */
  927       public void interrupt() {
  928           if (this != Thread.currentThread())
  929               checkAccess();
  930   
  931           synchronized (blockerLock) {
  932               Interruptible b = blocker;
  933               if (b != null) {
  934                   interrupt0();           // Just to set the interrupt flag
  935                   b.interrupt(this);
  936                   return;
  937               }
  938           }
  939           interrupt0();
  940       }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM