通常定义一个标记,来判断标记的状态停止线程的执行

/**
* @author VicterTian
* @version V1.0
* @Date 2018/12/11
*/
public class ThreadTest09 {
public static void main(String[] args) {
//Runnable r1 = new Processor();
Processor r1 = new Processor();
Thread t1 = new Thread(r1, "t1");
t1.start();
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
//停止线程
System.out.println("开始停止线程");
r1.setFlag();
}
}

class Processor implements Runnable {
//线程停止标记,true为停止
private Boolean flag = true;
public void run() {
for (int i = 1; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
if (flag) {
System.out.println(Thread.currentThread().getName() + "," + i);
}else{
break;
}
}
}
void setFlag() {
this.flag = false;
}
}