[英]Running Python scripts multithreaded in Java
I've written a small Java application which executes a Python script from multiple threads.我编写了一个从多个线程执行 Python 脚本的小型 Java 应用程序。 The Python script sends an SMS and the execution takes about 1-2 seconds. Python 脚本发送一条短信,执行大约需要 1-2 秒。
When only running 1 thread, all works well.当只运行 1 个线程时,一切正常。 But when using multiple threads, and the script needs to be executed multiple times (at the same time), not all threads succeed in the execution of the Python script.但是当使用多个线程,并且脚本需要多次(同时)执行时,并不是所有线程都能成功执行Python脚本。
All the threads contain the same "PythonExecutor" object.所有线程都包含相同的“PythonExecutor”对象。 The class contains these methodes.该类包含这些方法。 I'm using a synchronized methode.我正在使用同步方法。
public class PythonExecutor {
// Other stuff
public synchronized void runScript() {
String scriptFile = prefs.getScript();
try {
runPython(scriptFile);
} catch (Exception ex) {
...
}
}
private void runPython(String _scriptFile) throws IOException {
String[] cmd = {"python", _scriptFile,};
Runtime.getRuntime().exec(cmd);
}
}
Can anyone please tell me how I can solve this issue ?谁能告诉我如何解决这个问题?
Thanks谢谢
UPDATE !更新 !
I found a solution to my problem.我找到了解决我的问题的方法。 I've used ProcessBuilder instead of Runtime and it works perfectly.我使用了 ProcessBuilder 而不是 Runtime,它工作得很好。
private void runPython(String _scriptFile) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("python", _scriptFile);
Process p = pb.start();
p.waitFor();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.