启动类:启动一个线程,五秒后中断它。
线程类:
data代表数据
运行时让data无限加一,然后等待
中断时赋值为0,表示后续处理。
public class HelloDemo1 {
public static void main(String[] args) {
Thread t = new Thread(new MyTast());
t.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
}
static class MyTast implements Runnable {
private Integer data = 0;
@Override
public void run() {
Thread t = Thread.currentThread();
while (true) {
if (t.isInterrupted()) {
//此处为后续处理
data = 0;
System.out.println("End" + data);
break;
} else {
System.out.println(++data);
//重点,有等待,catch内部必须interrupt()
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
t.interrupt();
}
}
}
}
}
}
运行结果



