[英]InputStream - closing, interrupting blocking read()
某些输入-输出对象(例如InputStream
无法中断,并且在读取和写入期间无法关闭源。
例:
class InputStreamOperation1 implements Runnable
{
static InputStream stream;
InputStreamOperation1(InputStream stream) { this.stream = stream; }
public void run()
{
System.out.println("InputStreamOperation - the beginning");
try
{
stream.read(); //blocking operation
} catch (Exception e)
{
System.out.println("InputStreamOperation interrupted");
}
System.out.println("InputStreamOperation - the end");
}
}
尝试中断:
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting InputStream");
f.cancel(true); // Interrupts if running
System.out.println("Interrupt sent to InputStream");
试图关闭源
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Closing source in InpuStream");
try
{
System.in.close();
} catch (IOException e)
{
System.out.println("Error during closing InputStreamOperation");
}
System.out.println("Closed source in InputStream");
两种解决方案均无效。 阅读至少一个字母后,它会中断或关闭。
我的问题:在这种阻塞操作期间,有什么方法可以中断阻塞read()
操作或关闭源代码?
我在这里发现了类似的东西- 是否可以从InputStream中读取超时? 。 我想知道是否还有其他解决方案(尤其是使用中断或关闭源代码)来停止线程,或者是否只有一个棘手的方式被连接。
两种解决方案均无效。 阅读至少一个字母后,它会中断或关闭。
关闭System.in
对我System.in
。
我的输出显示:
InputStreamOperation - the beginning
Closing source in InpuStream
Closed source in InputStream
read: -1
InputStreamOperation - the end
我添加了读取结果的打印,当我在另一个线程中关闭System.in
时,它显示-1
表示EOF。
我想知道您的问题是否在于您没有关闭ExecutorService
吗? 如果您不这样做,那么您的申请将无法完成。
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
executor.shutdown();
如果仍然无法使用,则必须取决于操作系统。 它适用于OSX和Linux。
我的问题:在这种阻塞操作期间,有什么方法可以中断阻塞read()操作或关闭源代码?
除了关闭一直对我有用的流之外,我知道的另一种方法是使用NIO InterruptibleChannel
类并中断它。
编辑:
根据评论,您正在Netbeans下工作,可能是Web包装程序出于安全目的以某种方式保护了System.in
.。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.