Java中終止線程的三種方法_java

來源:互聯網
上載者:User

Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 這些終止線程啟動並執行方法已經被廢棄,使用它們是極端不安全的!

1.線程正常執行完畢,正常結束

也就是讓run方法執行完畢,該線程就會正常結束。

但有時候線程是永遠無法結束的,比如while(true)。

2.監視某些條件,結束線程的不間斷運行

需要while()迴圈在某以特定條件下退出,最直接的辦法就是設一個boolean標誌,並通過設定這個標誌來控制迴圈是否退出。

public class ThreadFlag extends Thread {  public volatile boolean exit = false;  public void run() {    while (!exit) {      System.out.println("running!");    }  }  public static void main(String[] args) throws Exception {    ThreadFlag thread = new ThreadFlag();    thread.start();    sleep(1147); // 主線程延遲5秒    thread.exit = true; // 終止線程thread     thread.join();    System.out.println("線程退出!");  }}

3.使用interrupt方法終止線程

如果線程是阻塞的,則不能使用方法2來終止線程。

public class ThreadInterrupt extends Thread {  public void run() {    try {      sleep(50000); // 延遲50秒    } catch (InterruptedException e) {      System.out.println(e.getMessage());    }  }  public static void main(String[] args) throws Exception {    Thread thread = new ThreadInterrupt();    thread.start();    System.out.println("在50秒之內按任意鍵中斷線程!");    System.in.read();    thread.interrupt();    thread.join();    System.out.println("線程已經退出!");  }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.