java cancel_Future.cancel()疑难杂症

在学习Java并发编程时,对于Future的cancel()方法产生了疑问。当调用cancel()方法后,线程并未截获中断信号,isCanceled()却返回true。示例代码中展示了两种情况:1. 不检查isInterrupted()时,线程仍继续运行;2. 对于睡眠中的线程,cancel()似乎并未唤醒线程。期待解析这一现象,并寻求更多并发编程书籍推荐。

问题描述

在学习并发编程的时候对Future的cancel有点小疑惑。

future类里面,有cancel()和isCanceled()的两个方法,前者是发送取消命令给线程并返回是否发送成功,后者是判断该线程是否被取消。但是在实际运用时出现了一些问题。以下会列出问题:

问题出现的环境背景及自己尝试过哪些方法

查阅了《java并发编程》,发现书里对isCanceled没有详细介绍

相关代码

问题

1.我对线程发送了cancel命令,但没有用isInterrupted来截获cancel命令,也就是说,线程还能一直执行下去。为什么isCanceled()返回了true呢?

public class Test10 {

class MyCallable implements Callable {

@Override

public String call() throws Exception {

int i = 0;

while (i == 0) {

System.out.println("z");

}

return "always run";

}

}

public static void main(String[] args) throws InterruptedException {

Test10 test10 = new Test10();

MyCallable myCallable = test10.new MyCallable();

ExecutorService executorService = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new LinkedBlockingDeque());

Future future = executorService.submit(myCallable);

Thread.sleep(4000);

System.out.println(future.cancel(true) + " " + future.isCancelled());

}

}

这个是返回结果:

a1919ea069d50234b9d90943c707f9f6.png

2.当我对sleep的线程发出cancel命令,会发生什么呢?我试了下好像会一直处于sleep状态了

public class Test10 {

class MyCallable implements Callable {

@Override

public String call() throws Exception {

int i = 0;

while (i == 0) {

if (Thread.currentThread().isInterrupted()) {

System.out.println("截获中断");

}

Thread.sleep(1000);

System.out.println("z");

}

return "always run";

}

}

public static void main(String[] args) throws InterruptedException {

Test10 test10 = new Test10();

MyCallable myCallable = test10.new MyCallable();

ExecutorService executorService = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 5, TimeUnit.SECONDS, new LinkedBlockingDeque());

Future future = executorService.submit(myCallable);

Thread.sleep(4000);

System.out.println(future.cancel(true) + " " + future.isCancelled());

}

}

这个是返回结果:

cc1db2e1922c4941f427be433ed5f947.png

你期待的结果是什么?实际看到的错误信息又是什么?

希望有大牛解惑,另外可以推荐一些并发编程的书吗?我看了《java并发编程:核心方法与框架》以及《java并发编程实战》了,总感觉学的比较浅。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值