package com.chengguo.線程;
import java.util.Scanner;
/**
* 測試stop
* ①建議線程正常中止--->利用次數,不建議死循環
* ②建議使用標誌位----->設置一個標誌位
* ③不要使用stop或destroy等過期或者JDK不建議使用的方法
*/
public class Demo_20200509006_StopThread implements Runnable {
//設置一個標誌位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag)
System.out.println("run……" + i++);
}
//設置一個公開的方法中止線程,轉換標誌位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
//插入鍵盤輸入的知識
Scanner scanner = new Scanner(System.in);
System.out.println("輸入你想要中止的輸:");
int enterNum = scanner.nextInt();
Demo_20200509006_StopThread dst = new Demo_20200509006_StopThread();
new Thread(dst).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main:" + i);
if (i == enterNum) {
//調用stop方法切換標誌位,讓線程中止
dst.stop();
System.out.println("線程中止……");
}
}
}
}