借助抛异常停止
package top.yuyufeng.demo.thread;
/**
* @author yuyufeng
* @date 2019/2/21.
*/
public class Demo1Threadinterrupted {
public static void main(String[] args) {
try {
MyThread t1 = new MyThread();
t1.start();
Thread.sleep(1000);
t1.interrupt();
System.out.println("是否停止:" + t1.isInterrupted());
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}
class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
if (this.isInterrupted()) {
System.out.println("线程已经终止");
throw new InterruptedException();
}
}
System.out.println("线程快结束了!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
借助return停止
class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
if (this.isInterrupted()) {
System.out.println("线程已经终止");
return;
}
}
System.out.println("线程快结束了!");
}
}
建议使用抛异常的方式进行停止,能更好的控制流程