如何正确而优雅的终止运行中的线程

一、使用volatile [ˈvɑ:lətl] (不稳定的)标志位

首先,实现一个Runnable接口,在其中定义volatile标志位,在run()方法中使用标志位控制程序运行。

  1. public class MyRunnable implements Runnable {
  2.  
  3. //定义退出标志,true会一直执行,false会退出循环
  4. //使用volatile目的是保证可见性,一处修改了标志,处处都要去主存读取新的值,而不是使用缓存
  5. public volatile boolean flag = true;
  6.  
  7. public void run() {
  8. System.out.println("第" + Thread.currentThread().getName() + "个线程创建");
  9.  
  10. try {
  11. Thread.sleep(1000L);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15.  
  16. //退出标志生效位置
  17. while (flag) {
  18. }
  19. System.out.println("第" + Thread.currentThread().getName() + "个线程终止");
  20. }
  21. }

然后,在main()方法中创建线程,在合适的时候,修改标志位,终止运行中的线程。

  1. public class TreadTest {
  2. public static void main(String[] arg) throws InterruptedException {
  3. MyRunnable runnable = new MyRunnable();
  4.  
  5. //创建3个线程
  6. for (int i = 1; i <= 3; i++) {
  7. Thread thread = new Thread(runnable, i + "");
  8. thread.start();
  9. }
  10. //线程休眠
  11. Thread.sleep(2000L);
  12. System.out.println("——————————————————————————");
  13. //修改退出标志,使线程终止
  14. runnable.flag = false;
  15. }

3、使用interrupt()中断的方式,注意使用interrupt()方法中断正在运行中的线程只会修改中断状态位,可以通过isInterrupted()判断。如果使用interrupt()方法中断阻塞中的线程,那么就会抛出InterruptedException异常,可以通过catch捕获异常,然后进行处理后终止线程。有些情况,我们不能判断线程的状态,所以使用interrupt()方法时一定要慎重考虑。

看一个简单的例子(中断运行中的线程):

  1. public class MyRunnable2 implements Runnable{
  2.  
  3. public void run(){
  4. System.out.println(Thread.currentThread().getName() + " 线程创建");
  5. try {
  6. Thread.sleep(1000L);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. //运行时的线程被中断后,只会修改中断标记,不会抛出异常
  11. while(Thread.currentThread().isInterrupted()){
  12.  
  13. }
  14. System.out.println(Thread.currentThread().getName() + " 线程被中断");
  15. }
  16.  
  17. }
  1. public class TreadTest {
  2. public static void main(String[] arg) throws InterruptedException {
  3. Runnable runnable = new MyRunnable2();
  4.  
  5. //创建3个线程
  6. Thread thread1 = new Thread(runnable, "1");
  7. Thread thread2 = new Thread(runnable, "2");
  8. Thread thread3 = new Thread(runnable, "3");
  9. thread1.start();
  10. thread2.start();
  11. thread3.start();
  12.  
  13. //线程休眠
  14. Thread.sleep(2000L);
  15.  
  16. //修改退出标志,使线程终止
  17. thread1.interrupt();
  18. thread2.interrupt();
  19. thread3.interrupt();
  20. }

猜你喜欢

转载自blog.csdn.net/u012325073/article/details/81511591