java线程无限循环_如何强制停止无限循环线程

如果你暴露线程执行程序让你运行,那么你可以打断它。对我来说,这只打印14次表明中断成功。

请记住,这依赖于一个事实,即Thread.sleep和System.out.println是中断的。如果你没有检查Thread.isInterrupted(就像他们两个那样),你仍然可能无法中断线程。ExecutorService executor = Executors.newSingleThreadExecutor();private void test() throws InterruptedException {

AtomicReference thread = new AtomicReference<>();

Future task = executor.submit(() -> {

// Keep track of the thread.

thread.set(Thread.currentThread());

try {

while (true) {

Thread.sleep(1000);

System.out.println("1");

}

} finally {

System.out.println("Interrupted: " + Thread.currentThread().isInterrupted());

}

});

Thread.sleep(5000);

// Interrupt the thread.

thread.get().interrupt();

Thread.sleep(5000);

System.out.println("Press  to shutdown");

new Scanner(System.in).nextLine();

executor.shutdown();

System.out.println("Press  to shutdown NOW");

new Scanner(System.in).nextLine();

executor.shutdownNow();}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值