这一章节我们来讨论一下迫使线程停止的方法-异常法。
1.伪停止法
在介绍异常法前,我们来看一下一个伪停止的例子。
一般使用多线程,都是在执行一些循环任务,那么,我只要停止了for,就停止了线程了,这是错误的。
例子
package com.ray.deepintothread.ch01.topic_6;
public class FakeInterruptSample {
public static void main(String[] args) throws InterruptedException {
ThreadFive threadFive = new ThreadFive();
threadFive.start();
threadFive.interrupt();
}
}
class ThreadFive extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (Thread.interrupted()) {
System.out.println("退出循环");
break;
}
System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
try {
sleep(50);
} catch (InterruptedException e) {
}
}
System.out.println("测试数据");
super.run();
}
}
输出:
退出循环
测试数据
从上面可以看出,虽然我们退出了循环,但是线程还是继续执行的
2.异常法
package com.ray.deepintothread.ch01.topic_6;
public class InterruptWithExceptionSample {
public static void main(String[] args) throws InterruptedException {
ThreadSix threadSix = new ThreadSix();
threadSix.start();
}
}
class ThreadSix extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
System.out.println("退出线程");
throw new RuntimeException();
}
System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
try {
sleep(50);
} catch (InterruptedException e) {
}
}
System.out.println("测试数据");
super.run();
}
}
输出:
interrupt:false
interrupt:false
interrupt:false
退出线程
Exception in thread "Thread-0" java.lang.RuntimeException
at com.ray.deepintothread.ch01.topic_6.ThreadSix.run(InterruptWithExceptionSample.java:17)
从输出可以看见,当我们抛出异常的时候,线程就直接停止了,但是有一点需要注意的是,不能catch这个异常,不然这个不起作用
不起作用的异常:
package com.ray.deepintothread.ch01.topic_6;
public class InterruptWithExceptionSample2 {
public static void main(String[] args) throws InterruptedException {
ThreadOne threadOne = new ThreadOne();
threadOne.start();
}
}
class ThreadOne extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i == 3) {
System.out.println("想退出");
try {
throw new RuntimeException();
} catch (RuntimeException e) {
}
}
System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
try {
sleep(50);
} catch (InterruptedException e) {
}
}
System.out.println("测试数据");
super.run();
}
}
输出:
interrupt:false
interrupt:false
interrupt:false
想退出
interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false
interrupt:false
测试数据
从上面的输出可以看见,线程的运行并没有停止。
总结:这一章节主要讲述了退出线程的方法-异常法。
我的github:https://github.com/raylee2015/DeepIntoThread