灵活运用标记 boolean 来达到终止程序的可控的,具体如下所示 对你有帮助的话给个赞
public class ThreadTest08 {
public static void main(String[] args) {
MyRunnable4 r = new MyRunnable4();
Thread t = new Thread(r);
t.setName("t");
t.start();
// 模拟5秒
try {
t.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 更改标记
r.run = false;
}
}
class MyRunnable4 implements Runnable{
boolean run = true;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (run){
System.out.println(Thread.currentThread().getName() + "==>" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
// 终止当前线程
return;
}
}
}
}