[英]How to stop a thread waiting in a blocking read operation in Java?
我有一个执行以下代码的线程:
public void run() {
try {
int n = 0;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
out.flush();
}
} catch (IOException e) {
System.out.println(e);
}
}
其中, in
是System.in
。 我怎样才能优雅地停止这样的线程? 关闭System.in
,使用Thread.interrupt
似乎都不起作用。
这是因为读取System.in(InputStream)是一个阻塞操作。
您可以使用available()方法(非阻塞)来检查是否有事先要读取的内容。
在伪java中:
//...
while(running)
{
if(in.available() > 0)
{
n = in.read(buffer);
//do stuff with the buffer
}
else
{
Thread.sleep(500);
}
}
//when running set to false exit gracefully here...
我今天遇到了同样的问题,这就是我使用in.ready()
修复它的方法:
public void run() {
String line;
// Some code
while(!Thread.currentThread().isInterrupted()){
try {
if (in.ready()) {
line = in.readLine();
}
} catch (Exception e) {
try {
Thread.currentThread().wait(500);
} catch (InterruptedException e1) {
// Do what we want when thread is interrupted
}
}
}
}
在其他线程中关闭流是否安全? 这个对我有用。 在这种情况下, in.read(...)
抛出异常SocketException
。
如果您想给用户一些时间来输入数据 - 可能允许覆盖默认值或中断某些自动过程 - 然后先等待并在暂停后检查可用输入:
System.out.println("Enter value+ENTER within 5 Seconds to override default value: ");
try{
Thread.sleep(5000);
} catch {InterruptedException e){}
try{
int bytes = System.in.available();
if (bytes > 0) {
System.out.println("Using user entered data ("+size+" bytes)");
} else {
System.out.println("Using default value");
}
} catch(IOException e) { /*handle*/ }
你可以使用外部标志
boolean flag = true;
public void run() {
try {
int n = 0;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer)) != -1 && flag) {
out.write(buffer, 0, n);
out.flush();
}
} catch (IOException e) {
System.out.println(e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.