国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

Java 線程中斷

2020-11-09 10:23 更新

Java線程教程 - Java線程中斷


我們可以通過使用interrupt()方法中斷一個(gè)活動(dòng)的線程。

這個(gè)方法調(diào)用在線程只是一個(gè)指示。它是由線程如何響應(yīng)中斷。

例子

下面的代碼顯示了中斷主線程并打印線程中斷狀態(tài)的代碼。

public class Main {
  public static void main(String[] args) {
    System.out.println("#1:" + Thread.interrupted());

    // Now interrupt the main thread
    Thread.currentThread().interrupt();

    // Check if it has been interrupted
    System.out.println("#2:" + Thread.interrupted());

    // Check again if it has been interrupted
    System.out.println("#3:" + Thread.interrupted());
  }
}

上面的代碼生成以下結(jié)果。

例2

下面的代碼如何一個(gè)線程將中斷另一個(gè)線程。

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::run);
    t.start();
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    t.interrupt();
  }

  public static void run() {
    int counter = 0;
    while (!Thread.interrupted()) {
      counter++;
    }
    System.out.println("Counter:" + counter);
  }
}

上面的代碼生成以下結(jié)果。


例3

Thread類有一個(gè)非靜態(tài)的isInterrupted()方法,可以用來測試一個(gè)線程是否被中斷。

public class Main {
  public static void main(String[] args) {
    System.out.println("#1:" + Thread.interrupted());

    Thread mainThread = Thread.currentThread();
    mainThread.interrupt();

    System.out.println("#2:" + mainThread.isInterrupted());

    System.out.println("#3:" + mainThread.isInterrupted());

    System.out.println("#4:" + Thread.interrupted());

    System.out.println("#5:" + mainThread.isInterrupted());
  }
}

上面的代碼生成以下結(jié)果。

例4

你可以中斷一個(gè)被阻塞的線程。

如果在這三種方法上阻塞的線程被中斷,則拋出一個(gè)InterruptedException,并清除線程的中斷狀態(tài)。

以下代碼啟動(dòng)一個(gè)休眠一秒的線程,并打印一條消息,直到它被中斷。

public class Main {
  public static void main(String[] args) throws InterruptedException{
    Thread t = new Thread(Main::run);
    t.start();
    Thread.sleep(5000);
    t.interrupt();
  }

  public static void run() {
    int counter = 1;
    while (true) {
      try {
        Thread.sleep(1000);
        System.out.println("Counter:" + counter++);
      } catch (InterruptedException e) {
        System.out.println("I got  interrupted!");
      }
    }
  }
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號