结合join,interrupt和daemon暴力中断线程

daemon:将线程设置为守护线程,调用线程结束后守护线程也跟着结束

join:调用join的线程只有结束后其他线程才会执行

interrupt:将线程中断,stop有风险被停用

结合join,interrupt和daemon暴力中断线

ThreadService

public class ThreadService {

  private Thread excuteThread;
  private boolean finished = false;
  public void excute(Runnable runnable) {
    excuteThread = new Thread() {
      @Override
      public void run() {
        Thread inner = new Thread(runnable);
        // 将inner设置成守护线程,这样调用它的线程结束后,inner线程也跟着结束
        inner.setDaemon(true);
        inner.start();
        try {
          // 执行完inner线程才会去执行别的线程,但是如果调用它的线程超时被中断,这个线程也会跟着中断
          inner.join();
          finished = true;
        } catch (InterruptedException e) {

        }
      }
    };
    excuteThread.start();
  }

  public void shutdown(long mills) {
    long current = System.currentTimeMillis();
    while (!finished) {
      // 系统当前时间-进入shutdown方法的时间,如果超时,直接中断
      if ((System.currentTimeMillis()-current)>=mills) {
        System.out.println("任务超时");
        excuteThread.interrupt();
        break;
      }
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
        break;
      }
    }
    finished = false;
  }
}

ThreadCloseForce

public class ThreadCloseForce {

  private static volatile int i = 0;

  public static void main(String[] args) {
    ThreadService threadService = new ThreadService();
    long start = System.currentTimeMillis();
    threadService.excute(
        () -> {
          while (true) {
            System.out.println(Thread.currentThread().getName() + "running..." + i++);
          }
//                try {
//                  Thread.sleep(5_000);
//                } catch (InterruptedException e) {
//                  e.printStackTrace();
//                }
        });

    threadService.shutdown(8000);
    long end = System.currentTimeMillis();
    System.out.println(end - start);
  }
}

在这里插入图片描述

超时时间设置为8s,但是线程结束为8055,说明中断线程也需要时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐观的Terry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值