gpt4 book ai didi

java - StreamGobbler - 接受输入的线程? java

转载 作者:太空宇宙 更新时间:2023-11-04 15:19:23 25 4
gpt4 key购买 nike

使用自编的StreamGobbler来运行php脚本,我正在尝试在脚本运行时将命令输入到脚本中...

StreamGobbler.java

private class StreamGobbler extends Thread {
InputStream is;
OutputStream os;
String line;
PMRunnerPro main;

public StreamGobbler(InputStream is, OutputStream os, PMRunnerPro main) {
this.is = is;
this.os = os;
this.main = main;
}

@Override
public void run() {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));


line = reader.readLine();
while (line != null && ! line.trim().equals("--EOF--")) {
if (main.sSendNeeded) {
System.out.println("Sent");
writer.write(main.sCommand + "\n");

main.sSendNeeded = false;
main.sCommand = "";
}
main.outputBox.setText(main.outputBox.getText() + (line + "\n"));
line = reader.readLine();
}
writer.flush();

} catch(IOException ex) {
main.sRunning = false;
}

System.out.println("Over");
main.sRunning = false;
}
}

仅当脚本有输出时,命令才会发送到脚本。

我希望线程不断检查是否有任何命令要发送到脚本,如果有则执行此操作。

最佳答案

如果我正确理解了你的意图...

由于您使用阻塞 I/O,因此您需要两个线程来实现您想要的功能:

  • 第一个线程将读取脚本输出,就像您现在所做的那样。一旦输出可用,它将显示在文本区域中;
  • 第二个线程将从队列中读取输入并将其转发给脚本。

这是代码草稿(请注意,您可能希望在输入和输出工作器之间添加同步,因此输入工作器将无法向脚本发送新命令,直到上一个命令从脚本生成输出,但这取决于您):

class InputWorker implements Runnable {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
String line = reader.readLine();
while (line != null && ! line.trim().equals("--EOF--")) {
// show script output
}
} catch(IOException ex) {
//
}
}
}

class OutputWorker implements Runnable {
final BlockingQueue<String> commandQueue = new ArrayBlockingQueue<String>();

public void sendCommand(String command) {
commandQueue.add(command);
}

@Override
public void run() {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));

while (true) {
String command = commandQueue.take();
if ("EXIT".equals(command)) { return; }
writer.write(command);
writer.flush();
}

} catch(IOException ex) {
//
} catch (InterruptedException e) {
//
}
}
}

关于java - StreamGobbler - 接受输入的线程? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20566267/

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