package charpter10;
public class Processor implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println("中断标记位:" + Thread.currentThread().isInterrupted());
System.out.println("状态:" + Thread.interrupted());
// 判断当前的线程中断标记位.如果是true则说明外界调用了interrupt方法,希望线程结束
if (Thread.currentThread().isInterrupted()) {
// 注意.线程结束之前.要做一些收尾工作
break;
}
System.out.println(Thread.currentThread().getName() + "-----------" + i);
}
}
}
---------------------------------
package charpter10;
/**
* 正确停止线程的方式三 使用Thread类中的内置的中断标记位
*/
public class TestInterrupt {
public static void main(String[] args) {
Processor p = new Processor();
Thread t1 = new Thread(p, "t1");
t1.start();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 将t1线程的中断标记位设置为true
t1.interrupt();
}
}