使用布林值停止 Java 執行緒


可以透過實現 Runnable 介面並重寫 run() 方法來建立執行緒。然後可以建立一個 Thread 物件並呼叫 start() 方法。

可以使用 Java 中的布林值停止執行緒。當布林值 stop 為 false 時,執行緒執行,當布林值 stop 變為 true 時,它停止執行。

演示此內容的程式如下所示

示例

class ThreadDemo extends Thread {
   public boolean stop = false;
   int i = 1;
   public void run() {
      while (!stop) {
         try {
            sleep(10000);
         } catch (InterruptedException e) {
         }
         System.out.println(i);
         i++;
      }
   }
}
public class Demo {
   public static void main(String[] args) {
      ThreadDemo t = new ThreadDemo();
      t.start();
      try {
         Thread.sleep(10000);
      } catch (InterruptedException e) {
      }
      t.stop = true;
      System.out.println("The thread is stopped");
   }
}

輸出

1
2
3
4
5
The thread is stopped

更新時間: 2019 年 7 月 30 日

823 次檢視

開啟您的職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.