前言
上篇文章讲解了多线程的两种创建方法,那么本文就带来多线程的停止方法。
一、线程的停止
1.stop方法
stop是jdk不推荐使用的一个方法,stop是强行停止一个线程,可能使一些清理性的工作得不到完成。还可能对锁定的内容进行解锁,容易造成数据不同步的问题,所以不推荐使用。
/**
* @version 1.0
* @Description 线程stop停止方式demo
* @Author wb.yang
*/
public class ThreadStopDemo {
public static class TestThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("this is :" + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
TestThread testThread = new TestThread();
testThread.start();
Thread.sleep(1);
testThread.stop();
}
}
如上面代码所示,启动了一个线程,循环了一万次输出,在启动后又调用了stop方法,停止了线程。
这个是代码运行的结果,从中可以看出,仅仅输出到44线程便停止了,在实际的应用中,很容易出现线程安全问题,所以不推荐使用。
2.interrupt方法
使用interrupt方法进行中断线程。interrupt是一个标识位,通过这个标识判断线程的状态,决定是否中断线程。通过代码来看一下把
/**
* @version 1.0
* @Description interrupt标识位demo
* @Author wb.yang
*/
public class InterruptDemo {
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss_SSS");
public static class TestThread extends Thread {
@Override
public void run() {
//判断中断标识位
while (!isInterrupted()) {
try {
//输出信息
System.out.println("UseThread:" + format.format(new Date()));
Thread.sleep(3000);
} catch (InterruptedException e) {
//检测到中断异常
System.out.println("UseThread catch interrput flag is "
+ isInterrupted() + " at "
+ (format.format(new Date())));
interrupt();
e.printStackTrace();
}
}
//线程终止结尾输出
System.out.println(" UseThread interrput flag is "
+ isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
TestThread testThread = new TestThread();
testThread.start();
//打印主线程时间
System.out.println("Main:" + format.format(new Date()));
Thread.sleep(800);
// 开始终止线程
System.out.println("Main begin interrupt thread:" + format.format(new Date()));
testThread.interrupt();
}
}
上面是使用interrupt方法进行终止线程,他给了线程的标识为true,然后在isInterrupted方法中判断标识状态,如果是true,终止状态,这终止线程。并且有一个InterruptedException异常,这个异常也是对标识位操作的处理。
这是输出结果,明显看出线程是执行完结束的。这个就较为线程安全,不像stop一样强行停止线程。
Thread.java提供了三个方法,interrupt主动进行停止线程,isInterrupted判断线程状态,不会清楚线程状态。interrupted方法会在检测的同时,如果发现标志为true,则会返回true,然后把标志置为false.
总结
线程停止还是不推荐使用stop,推荐使用interrupt方法,按照业务需求合理使用isInterrupted和interrupted方法来处理线程状态。