加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 你能用Future.cancel(true)中断BufferedReader.readLine

发布时间:2020-12-14 23:21:34 所属栏目:Java 来源:网络整理
导读:假设我开始了一个帖子,我有这样的事情: ...//initiate all the socket connection future = executor.submit ( new Runnable() { public void run() { ... ... while ((str = in.readLine()) != null) { //do something here } } ); executor是一个Executor
假设我开始了一个帖子,我有这样的事情:
...//initiate all the socket connection
 future = executor.submit
 (  new Runnable()
    {   public void run()
        {   ...
            ...      
            while ((str = in.readLine()) != null)
            {  //do something here

            }

    }

 );

executor是一个ExecutorService对象,并且是一个BufferedReader对象

我知道你可以从另一个线程关闭套接字来中断这个线程.但是当我尝试使用future.cancel(true)方法时,即使它返回true,线程似乎仍然在运行,任何人都知道为什么?或in.readLine()不能以这种方式中断?

解决方法

Can you interrupt BufferedReader.readLine() with Future.cancel(true)?

所有future.cancel(true)都是在关联的线程上调用thread.interrupt().这将导致sleep()和wait()操作抛出InterruptedException并将中断某些特殊的NIO channels.

但是很可能你的BufferedReader不会被中断,因为它很可能是从“普通”套接字或文件中读取的.正如您所提到的,从不同的线程关闭底层套接字是杀死这种IO方法的最佳方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读