gpt4 book ai didi

java - PipedInputStream 未被内部调用的 Java 程序读取

转载 作者:行者123 更新时间:2023-11-30 04:17:53 26 4
gpt4 key购买 nike

我正在编写一个程序,该程序通过使用 Class 和 Method 类调用 main 方法来执行另一个 Java 程序。然后,另一个程序尝试从 System.in 读取。为了将参数传递给程序,我将 System.in 设置为连接到 PipedOutputStream 的 PipedInputStream。我将其他程序请求的参数传递给 PipedOutputStream,然后调用 main 方法。
然而,一旦调用该方法,程序就会死锁。这是为什么?理论上,其他程序应该有权访问这些参数,因为它们已经在 PipedInputStream 中可用。
我无法更改其他程序读取输入的方式,因此该解决方案不起作用。

这里是一些示例代码:
我分配 PipedStreams 的部分

PipedInputStream inputStream = new PipedInputStream();
PipedStringOutputStream stringStream = new PipedStringOutputStream(); // custom class

try {
stringStream.connect(inputStream);
} catch (IOException e2) {
e2.printStackTrace();
}
System.setIn(inputStream);

我调用该方法的部分:

Class main = classes.get(className);
try {
Method m = main.getMethod("main", String[].class);

// write all parameters to System.in
String[] params = getParams(); // custom method, works (params is not empty)
for(int j = 0; j < params.length; j++) {
stringStream.write(params[j]);
}

params = null;
m.invoke(null, (Object) params); // this is were the program stops
} catch(Exception e) {}

PipedStringOutputStream 类:

public class PipedStringOutputStream extends PipedOutputStream {

public void write(String output) throws IOException {
this.write((output + "\n").getBytes());
flush();
}
}

我的测试程序从 System.in 读取:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println(sc.nextLine());
}
}

那么问题出在哪里呢?我必须在线程中启动流吗?为什么其他程序不从 PipedInputStream 读取输入?

最佳答案

PipedInputStream 的 javadoc 明确指出:

Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.

(强调我的)

使用ByteArrayOutputStream将输入写入字节数组。然后从此字节数组构造一个 ByteArrayInputStream,并将 System.in 设置为此 ByteArrayInputStream

关于java - PipedInputStream 未被内部调用的 Java 程序读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com