我有一个程序,它通过进程的输入和输出流与MPlayer通信。 它工作得很好,但我只能与主线程中的进程通信,而不能与其他任何进程通信。有没有可能得到这个?
synchronized-方法或块没有带来解决方案
private String getProperty(String property) {
System.out.println("CurThread: " + Thread.currentThread().getName());
String cmd = "";
cmd = String.format("pausing_keep_force get_property %s", property);
mplayerIn.println(cmd);
mplayerIn.flush();
String rightAnswer = String.format("ANS_%s=", property);
String errorAnswer = "ANS_ERROR";
String answer;
String value = "";
try {
while ((answer = mplayerOut.readLine()) != null) {
if (answer.startsWith(rightAnswer)) {
value = answer.substring(rightAnswer.length());
break;
}
if (answer.startsWith(errorAnswer)) {
value = "";
break;
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Property Error:" + property);
}
return value;
}
编辑:ProcessCommunicator
public class ProcessCommunicator extends Thread {
private String cmd;
private BufferedReader is;
private PrintStream os;
List<MessageReceivedListener> listeners;
public boolean addListener(MessageReceivedListener listener) {
return listeners.add(listener);
}
public boolean removeListener(MessageReceivedListener listener) {
if (listeners.contains(listener)) {
return listeners.remove(listener);
}
return false;
}
public ProcessCommunicator(String cmd) {
this.cmd = cmd;
listeners = new ArrayList<>();
}
public void write(String cmd) {
System.out.println(cmd);
os.println(cmd);
os.flush();
}
public void fireEvent(String msg) {
for (MessageReceivedListener listener : listeners) {
listener.received(msg);
}
}
Process p;
@Override
public void run() {
try {
p = Runtime.getRuntime().exec(cmd);
is = new BufferedReader(new InputStreamReader(p.getInputStream()));
os = new PrintStream(p.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
String line;
try {
while ((line = is.readLine()) != null) {
System.err.println(line);
fireEvent(line.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
}
boolean waitForProperty;
String propertyResult;
public String readProperty(String property) {
final String rightAnswer = String.format("ANS_%s=", property);
propertyResult = "";
MessageReceivedListener messageListener = new MessageReceivedListener() {
@Override
public void received(String s) {
if (s.startsWith(rightAnswer)) {
waitForProperty = false;
propertyResult = s.substring(rightAnswer.length());
} else if (s.startsWith("ANS_ERROR")) {
waitForProperty = false;
propertyResult = "";
}
}
};
addListener(messageListener);
waitForProperty = true;
write(String.format("pausing_keep_force get_property %s", property));
int i = 5;
while (waitForProperty && i > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(".");
i--;
}
System.out.println("END");
removeListener(messageListener);
return propertyResult;
}
}