I/O 阻塞 中断的注意点

---恢复内容开始---

shutdownNow() 方法:

  将向所有由ExecutorService 启动的任务发送 interrupt().进行阻断.

  但是只有任务进入到一个 (可中断的) 阻塞操作时,

  这个中断才会抛出 InterruptedExceptoin 异常.

 

需要注意的是:

[ I/O ] 和 [ synchronized 块上的等待 ] 是不可以中断的,只有通过关闭底层资源进行中断

所以在 创建I/O 任务的时候, 这意味着 I/O 具有锁住你的多线程程序的现在可能,

特别是对于基于 Web的程序.  但是nio 类的 I/O 是会自动响应中断的.

 

 

import java.sql.Time;
import java.util.*;
import java.util.concurrent.*;

class ioTest implements Runnable{
	int i =0;
	@Override
	public void run() {
		try {
			System.out.println("I can't be caught");
			TimeUnit.SECONDS.sleep(1);
		}catch(InterruptedException e) {
			System.out.println("Caught " + e );
		}
	}
}

public class Restaurant{
	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newCachedThreadPool();
		executorService.execute(new ioTest());//执行任务
		executorService.shutdownNow();
	}
}

  输出:

  1. I can't be caught
  2. Exit while
  3. Caught java.lang.InterruptedException: sleep interrupted

但是如果把TimeUnit.SECONDS.sleep() 放到最前面

import java.sql.Time;
import java.util.*;
import java.util.concurrent.*;

class ioTest implements Runnable{
	int i =0;
	@Override
	public void run() {
		try {
			TimeUnit.SECONDS.sleep(1);
			System.out.println("I can't be caught");
		}catch(InterruptedException e) {
			System.out.println("Caught " + e );
		}
	}
}

public class Restaurant{
	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newCachedThreadPool();
		executorService.execute(new ioTest());//执行任务
		executorService.shutdownNow();
	}
}

 输出:

  1. Caught java.lang.InterruptedException: sleep interrupted

 

可以得出:

  IO无法被阻断,但是TimeUnit.SECONDS.sleep 可以被阻断,并且抛出异常 InterruptedException

  如果要阻断IO 可以使用 System.out.close();

 

转载于:https://www.cnblogs.com/--zz/p/9657046.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值