簡體   English   中英

Java 6線程中斷

[英]java 6 Thread interrupt

我有這段代碼:

public class ThreadInteraction {
       public static void main(String[] argv) {
        System.out.println("Create and start a thread t1, then going to sleep...");
        Thread1 t1 = new Thread1();
        t1.start();


        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException e) {
            System.out.println(e.toString());
        }

            //let's interrupt t1
            System.out.println("----------- Interrupt t1");
        t1.interrupt();

        for(int i =0; i<100; i++)
            System.out.println("Main is back");
     }
}

class Thread1 extends Thread {
      public void run() {
         for(int i =0; i<10000; i++)
              System.out.println(i + "thread1");
      }
 }

似乎t1.interrupt()無法正常工作,因為在我的輸出中出現了所有10000 t1打印。 難道我做錯了什么?

Thread.interrupt()實際上不會停止任何操作。 此方法僅用於設置線程的中斷狀態,但是您必須檢查它。 這是組織代碼以使其正常工作的方式:

public void run() {
    for (int i = 0; i < 10000; i++) {
        if (interrupted()) break;
        System.out.println(i + "thread1");
    }
}

Thread.interrupted()此處清除中斷狀態,因為我們直接控制線程,所以可以。 如果您嘗試檢測中斷,例如,在java.util.concurrent. Callable 在線程池的線程之一上運行的java.util.concurrent. Callable ,則最好使用Thread.currentThread().isInterrupted(); 因為您不知道線程中斷策略。

Thread.interrupt僅在目標線程處於非常特定的狀態時才會導致目標線程停止:

首先,調用此線程的checkAccess方法,這可能會引發SecurityException。

如果在調用Object類的wait(),wait(long)或wait(long,int)方法或join(),join(long),join(long,int)方法時阻塞了此線程,sleep(long)或sleep(long,int)此類的方法,則其中斷狀態將被清除,並將收到InterruptedException。

如果此線程在可中斷通道的I / O操作中被阻止,則該通道將被關閉,線程的中斷狀態將被設置,並且該線程將收到ClosedByInterruptException。

如果此線程在選擇器中被阻塞,則該線程的中斷狀態將被設置,並且它將立即從選擇操作中返回,可能具有非零值,就像調用選擇器的喚醒方法一樣。

如果上述條件均不成立,則將設置該線程的中斷狀態。

如果要讓它盡早退出該循環,則需要檢查線程中的isInterrupted

for(int i =0; i<10000 && !isInterrupted(); i++)

暫無
暫無

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

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