jdk中,Thread类的stop方法不提供使用,那么如何优雅的停止线程?
看代码:
public class MyThread14 implements Runnable{
private boolean flag=true;
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (flag) {
System.out.println("hello,你好"+i);
}else {
break;
}
}
}
public void stop() {
this.flag = false;
System.out.println("我给你优雅的停止了线程");
}
public static void main(String[] args) throws InterruptedException {
MyThread14 myThread14 = new MyThread14();
System.out.println("启动");
new Thread(myThread14).start();
Thread.sleep(100);
myThread14.stop();//调用自己的stop方法停止线程
}
}