2017-04-09 174 views
0

我寫了一個小型的Java應用程序,它可以從多個線程執行Python腳本。 Python腳本發送一條短信,執行時間約爲1-2秒。在Java中運行多線程的Python腳本

當只運行1個線程時,一切正常。但是,當使用多個線程並且需要多次執行腳本(同時)時,並非所有線程都能成功執行Python腳本。

所有線程都包含相同的「PythonExecutor」對象。該類包含這些方法。我正在使用同步方法。

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); 
    } 

} 

任何人都可以請告訴我我該如何解決這個問題?

謝謝

回答

0

更新!

我找到了解決我的問題的方法。我使用了ProcessBuilder而不是Runtime,它可以很好地工作。

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