1.7 停止线程
停止线程是在多线程开发时很重要的技术点.掌握此技术可以对线程的停止进行有效的处理.
停止一个线程可以使用Thread.stop()方法,但是最好不要使用它.这个方法是不安全的.大多数停止一个线程的操作是使用Thread.interrupt().
1.7.1 停止不了的线程
调用interrupt()方法仅仅是在当前线程中打了一个停止的标记,并不是真的停止线程.
public class InterruptTest extends Thread{
@Override
public void run() {
super.run();
for(int i=1; i<500000; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
try {
Thread thread = new InterruptTest();
thread.start();
Thread.sleep(2000);
thread.interrupt();// 并没有终止线程,打印到500000
} catch (InterruptedException e) {
System.out.println("catch..");
}
}
}
1.7.2 判断线程是否是停止状态
在Java的SDK中,Thread类里提供了两种方法
1)this.interrupted():测试当前线程是否已经中断,当前线程是指this.interrupted()方法的线程
2)this.isInterrupted():测试线程是否已经中断
public class InterruptTest extends Thread{
@Override
public void run() {
super.run();
for(int i=0; i<500000; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
try {
Thread thread = new InterruptTest();
thread.start();
Thread.sleep(1000);
thread.interrupt();// 并没有终止线程
System.out.println("是否停止1?=" + thread.interrupted());// false
System.out.println("是否停止2?=" + thread.interrupted());// false
} catch (InterruptedException e) {
System.out.println("catch..");
}
System.out.println("end!");
}
}
以上代码的出来的结果,可以得出,线程并未停止,这也就是说明interrupt()方法的解释:测试当前线程是否已经中断,这个当前线程是main线程,它从未中断过,所以打印的结果是两个false.
public class MainInterruptTest extends Thread{
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止1?=" + Thread.interrupted());// true
System.out.println("是否停止2?=" + Thread.interrupted());// false 至于第二次返回false查看官方API
}
}
1.7.3 能停止的线程-异常法
public class ErrThread extends Thread{
@Override
public void run() {
super.run();
for(int i=1; i<=500000; i++){
if(this.isInterrupted()) {
System.out.println("thread is stopped, exist..");
break;
}
System.out.println("i = " + i);
}
}
public static void main(String[] args) {
try {
ErrThread thread = new ErrThread();
thread.start();
Thread.sleep(600);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");
}
}
i = 228743
i = 228744
end
thread is stopped, exist..
follow the for
上面的示例虽然停止了线程,但是还是会继续运行的.若要解决语句继续执行的问题,需要改造上面的方法
@Override
public void run() {
super.run();
try {
for(int i=1; i<=500000; i++){
if(this.isInterrupted()) {
System.out.println("thread is stopped, exist..");
throw new InterruptedException();
}
System.out.println("i = " + i);
}
System.out.println("follow the for");
} catch (InterruptedException e) {
e.printStackTrace();
}
}