1. 程式人生 > 其它 >JAVA基礎階段04---break與continue

JAVA基礎階段04---break與continue

執行緒狀態

  • 建立狀態
  • 就緒狀態
  • 執行狀態
  • 阻塞狀態
  • 死亡狀態

停止執行緒

  1. 不推薦使用JDK提供的stop()、destroy()方法
  2. 推薦執行緒自己停止下來
  3. 建議使用一個標誌位來終止變數,當flag=false,則終止執行緒執行
//測試stop
//1.建議執行緒正常停止---》利用次數,不建議死迴圈
//2.建議使用標誌位---》設定一個標誌位
//3.不要使用stop或者destroy等過失或者JDK不建議使用的方法
public class TestStop implements Runnable{

    //1.設定一個標誌位
    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("run...thread" + i++);
        }
    }

    //設定一個公開的方法停止執行緒,轉換標誌位
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main" + i);
            if (i == 900) {
                //呼叫停止
                testStop.stop();
                System.out.println("執行緒停止了");
            }
        }
    }
}