停止线程可以调用interrupt()方法,但是interrupt()方法的使用效果并不像for + break 语句那样,马上就停止循环。调用interrupt()方法仅仅是在当前线程中打了一个停止的标记。并不是真的停止线程。下面举个例子:
public class MyThread extends Thread {
@Override
synchronized public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(2000);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
}
}
运行main方法,
运行结果来看,并没有停止线程。我们还需要做些什么才能真正停止线程呢?
我们先看看如何判断线程的状态是不是停止呢?在Thread.java类里提供了两个方法。
- this.interrupted():测试当前线程是否已经中断
- this.isInterrupted():测试线程是否已经中断
我们先对第一个方法进行演示方便理解:
将上面的Run类修改下:
public class Run {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(3000);
myThread.interrupt();
System.out.println("是否停止1?=" + myThread.interrupted());
System.out.println("是否停止2?=" + myThread.interrupted());
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!!!!");
}
}
运行结果
因为这个当前线程是main主线程,它从没中断过,所以打印两个false;
如何让main线程产生中断效果呢?
public class Run2 {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止1?=" + Thread.interrupted());
System.out.println("是否停止2?=" + Thread.interrupted());
System.out.println("end!!!!");
}
}
结果:
结果来看:方法interrupted()的确判断出当前线程是否是停止状态。但是为什么第二个打印的是false呢?查阅官方文档得到的结论是interrupted()方法具有清除状态的功能。而isInterrupted()方法是不会清除状态的。
对了,前文的interrupted()方法是静态的 ,而isInterrupted()方法不是静态的。但返回值都是boolean类型