![](/img/trans.png)
[英]JPDA JDI ObjectReference of java.io.InputStreamReader
[英]Reading from standard input using java.io.InputStreamReader hangs when process runs in background
我正在編寫具有多個線程的Java程序。 線程之一負責從標准輸入中讀取行並進行解析。
正常運行時,一切正常,但是在后台(在Linux中)運行程序時,請使用:
$ java -jar my_jar_file &
我的程序掛起(至少一直掛到前台)。
在后台運行時,我實際上並不需要標准輸入,但也不想掛起我的程序。
我搜索了一種以編程方式確定該進程是否在后台運行但找不到的方法。
這是從標准輸入中讀取的代碼:
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = null;
try {
while ((line = br.readLine()) != null) {
parseInputLine(line, br);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
據我所知,該程序在到達br.readLine()
命令時掛起。
我想讀者可能會阻止等待輸入,您可能可以從命令行中輸入內容
readLine是一個阻止調用。 因此,顯然是在等待輸入。 如果您希望它在后台運行,則將這樣的文件的輸入傳遞給它
java TakeInput < test.txt &
該類如下,test.txt也如下所示:
public class TakeInput
{
public static void main(String[] args)
{
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
寫一個文本文件為test.txt其中說
test1
test2
test3
我不相信Java程序可以確定它是在前台運行還是在后台運行。
我嘗試了System.console()
,結果如下:
我懷疑您將需要從命令行調用該程序,因為
java -cp ... ClassName < /dev/null
嘗試使用.ready()函數。
try {
if (stdError.ready())
{
while((line= stdError.readLine()) != null){
logger.error(line);
}
}
}
對標准輸出執行相同的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.