zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    Eclipse里编辑代码,进度条出现“Remote System Explorer Operation”解决方法
    Fiddler快速入门
    十分钟学会 Fiddler
    网络抓包工具 wireshark 入门教程
    wireshark使用教程
    Apple iOS MDM开发流程
    input file 文件上传,js控制上传文件的大小和格式
    读取注册表获取Windows系统XP/7/8/10类型(使用wcscmp比较wchar[]内容)
    QT 序列化/串行化/对象持久化
    VC 使用msxml6.dll动态链接库中的函数读写XML文件
  • 原文地址:https://www.cnblogs.com/--zz/p/9657046.html
Copyright © 2011-2022 走看看