简体   繁体   中英

Running Python scripts multithreaded in Java

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

UPDATE !

I found a solution to my problem. I've used ProcessBuilder instead of Runtime and it works perfectly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM