Running Python scripts multithreaded in Java

时间:2017-04-09 23:54:44

标签: java python multithreading

I've written a small Java application which executes a Python script from multiple threads. The Python script sends an SMS and the execution takes about 1-2 seconds.

When only running 1 thread, all works well. 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.

All the threads contain the same "PythonExecutor" object. 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

1 个答案:

答案 0 :(得分:0)

更新!

我找到了解决问题的方法。我使用过ProcessBuilder而不是Runtime,它运行得很好。

  private void runPython(String _scriptFile) throws IOException, InterruptedException {
              ProcessBuilder pb = new ProcessBuilder("python", _scriptFile);
              Process p = pb.start();
              p.waitFor();
  }