比较好的实现方式
示例代码
public class InterruptThread implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("线程正在运行...");
long time = System.currentTimeMillis();
int count = 0;
while ((System.currentTimeMillis() - time) < 1000) {
}
// 中断一个线程
if (Thread.currentThread().isInterrupted()) {
break;
}
}
System.out.println(Thread.currentThread().getName() + "线程结束");
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new InterruptThread(), "testThread");
System.out.println("线程开始");
thread.start();
Thread.sleep(3000);
System.out.println("线程是否中断" + thread.isInterrupted());
System.out.println("开始中断线程");
thread.interrupt();
System.out.println("线程是否中断" + thread.isInterrupted());
Thread.sleep(5000);
System.out.println("线程" + Thread.currentThread().getName() + "结束");
}
}
运行结果如下:
线程开始
线程正在运行...
线程正在运行...
线程正在运行...
线程正在运行...
线程是否中断false
开始中断线程
线程是否中断true
testThread线程结束
线程main结束