Channel(一):可中断的能力

本文探讨了NIO Channel的中断能力,重点讲解了AbstractInterruptibleChannel类如何实现中断Channel。通过begin()方法创建Interruptible接口对象并绑定到线程,当调用thread.interrupt()时,Channel的open属性变为false,引发ClosedChannelException或AsynchronousCloseException。此外,还介绍了AbstractInterruptibleChannel的关闭方法和相关异常处理。
摘要由CSDN通过智能技术生成

NIO的Channel可中断的能力

Channel可相应中断进入关闭状态。

关键在于使用AbstractInterruptibleChannel的begin()和end(completed)方法。

1、在begin()方法中 创建了Interruptible接口的对象 interruptor中断器,并使用blockOn(interruptor)方法,将interruptor绑定到当前线程的blocker属性。

2、当使用thread.interrupt()方法时首先会设置线程的中断标志位。然后调用blocker的interrupt(target)方法,改变Channel的open属性为false,然后将target赋值给Channel的interrupted属性。最后调用implCloseChannel()方法,先关闭Channel,再将Channel注册的所有SelectionKey取消注册。

3、enq(completed)方法进行最后的处理有可能会抛出ClosedChannelException(对已经关闭的Channel进行I/O操作)和 AsynchronousCloseException(对I/O操作没有结束的Channel进行中断取消)

解读

AbstractInterruptibleChannel类:可中断Channel的基本实现类

public abstract class AbstractInterruptibleChannel
    implements Channel, InterruptibleChannel{
   

1、AbstractInterruptibleChannel实现了Channel和InterruptibleChannel接口

1)、public interface Channel extends Closeable {

  • public boolean isOpen();:判断Channel是否打开
  • public void close() throws IOException;:关闭Channel(已经关闭无影响)。如果对已经关闭的channel进行I/O请求,会抛出ClosedChannelException异常。

2)、public interface InterruptibleChannel extends Channel{

  • public void close() throws IOException;:如果在没有完成I/O操作的时候对channel进行关闭会抛出 AsynchronousCloseException异常。

2、使用的方法简介

boolean completed = false;
 try {
   
     begin();
     completed = ...;    // Perform blocking I/O operation
     
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值