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("线程中止……");
}
}
}
}