NIO响应中断
程序员文章站
2022-07-12 19:28:50
...
不同于IO,NIO通道会自动地相应中断,代码如下:
public class NIOBlocked implements Runnable{
private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) {
this.sc=sc;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Wating to read in");
try {
sc.read(ByteBuffer.allocate(1));
}catch(ClosedByInterruptException ex){
System.out.println("ClosedByInterruptException...");
}catch(AsynchronousCloseException ae){
System.out.println("AsynchronousCloseException...");
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException...");
}
System.out.println("Exit NIOBlocked.run()");
}
}
==============================
public class NIOInterruption {
public static void main(String[] args) throws IOException, InterruptedException{
ExecutorService exec=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(9111);
InetSocketAddress isa=new InetSocketAddress("localhost",9111);
SocketChannel sc1=SocketChannel.open(isa);
SocketChannel sc2=SocketChannel.open(isa);
Future<?> f=exec.submit(new NIOBlocked(sc1));
exec.execute(new NIOBlocked(sc2));
exec.shutdown();
TimeUnit.SECONDS.sleep(1);
f.cancel(true);//这里可以产生中断
TimeUnit.SECONDS.sleep(1);
sc2.close();
}
}
public class NIOBlocked implements Runnable{
private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) {
this.sc=sc;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Wating to read in");
try {
sc.read(ByteBuffer.allocate(1));
}catch(ClosedByInterruptException ex){
System.out.println("ClosedByInterruptException...");
}catch(AsynchronousCloseException ae){
System.out.println("AsynchronousCloseException...");
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException...");
}
System.out.println("Exit NIOBlocked.run()");
}
}
==============================
public class NIOInterruption {
public static void main(String[] args) throws IOException, InterruptedException{
ExecutorService exec=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(9111);
InetSocketAddress isa=new InetSocketAddress("localhost",9111);
SocketChannel sc1=SocketChannel.open(isa);
SocketChannel sc2=SocketChannel.open(isa);
Future<?> f=exec.submit(new NIOBlocked(sc1));
exec.execute(new NIOBlocked(sc2));
exec.shutdown();
TimeUnit.SECONDS.sleep(1);
f.cancel(true);//这里可以产生中断
TimeUnit.SECONDS.sleep(1);
sc2.close();
}
}
上一篇: Jquery Ajax 异步请求
推荐阅读
-
详解Koa中更方便简单发送响应的方式
-
JavaScript使用类似break机制中断forEach循环的方法
-
实战SpringCloud响应式微服务系列教程(第九章)使用Spring WebFlux构建响应式RESTful服务
-
apache中使用mod_log_slow分析响应慢的请求
-
微软发布Windows 10 20H1/20H2更新:修复无响应等问题
-
Python wxpython模块响应鼠标拖动事件操作示例
-
时代在召唤,B2B电商如何响应电商“大航海时代”
-
响应式网站建设:为什么它对您来说很重要
-
java线程阻塞中断与LockSupport使用介绍
-
怎样玩转响应式Logo设计 快速建立品牌形象?