java sleep 抛出异常_java.lang.InterruptedException: sleep interrupted

以下是main函数中的代码,想测试一下shutdownNow的效果。

public class TestLa {

public static void main(String... args){

/*省略了一段无意义的测试代码*/

ExecutorService executorService = Executors.newFixedThreadPool(2);

class Task implements Callable {

public int id;

Task(int id) {

this.id = id;

}

@Override

public Integer call() throws Exception {

System.out.println(String.format("我的id是:%s,开始计算>>>...",id));

int sum = 0;

for(int i = 0; i < 100; i++){

sum += i;

Thread.sleep(100);

}

System.out.println(String.format("我的id是:%s,执行结束>>>...",id));

return sum;

}

}

Future future = executorService.submit(new Task(1));

executorService.submit(new Task(2));

executorService.submit(new Task(3));

executorService.submit(new Task(4));

List tasksWaitExecutingList = executorService.shutdownNow();

System.out.println("我们在执行器结束时未完成:");

for(Runnable item : tasksWaitExecutingList) {

Thread thisThread = new Thread(item);

thisThread.start();

}

/*executorService.shutdown();*/

try {

System.out.println("计算结果:"+ future.get());

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

}

}

程序运行的结果:

我们在执行器结束时未完成:

我的id是:3,开始计算>>>...

我的id是:1,开始计算>>>...

我的id是:2,开始计算>>>...

我的id是:4,开始计算>>>...

java.util.concurrent.ExecutionException: java.lang.InterruptedException: sleep interrupted

at java.util.concurrent.FutureTask.report(FutureTask.java:122)

at java.util.concurrent.FutureTask.get(FutureTask.java:188)

at com.mq.xx.entrust.action.TestLa.main(TestLa.java:137)

Caused by: java.lang.InterruptedException: sleep interrupted

at java.lang.Thread.sleep(Native Method)

at com.mq.xx.entrust.action.TestLa$1Task.call(TestLa.java:116)

at com.mq.xx.entrust.action.TestLa$1Task.call(TestLa.java:1)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:745)

我的id是:4,执行结束>>>...

我的id是:3,执行结束>>>...

不知道主线程退出怎么中断了其他线程的,这里调用 future.get() 并不会阻塞主线程。而运行executorService.shutdown(),而不是shutdownNow的时候,程序不会抛出异常,主线程会阻塞到future.get()有返回的时候,不太明白

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值