使用线程和ProcessBuilder

knt*_*knt 2 java multithreading process processbuilder

我对使用线程非常不熟悉,所以我希望有人可以帮我找出最好的方法.

我的java应用程序中有一个JButton ...当你点击按钮时,我有一个Process Builder,它创建一个执行一些外部python代码的进程.python代码生成一些文件,这可能需要一些时间.当python代码完成执行时,我需要将这些文件加载​​到我的Java应用程序中的applet中.

在其当前形式中,我在调用外部python文件的代码中有一个p.waitFor()...所以当你单击按钮时,按钮会挂起(整个应用程序实际挂起),直到完成该过程.显然,我希望用户能够在此过程进行时与应用程序的其余部分进行交互,但是一旦完成,我希望我的应用程序知道它,以便它可以将文件加载到applet中.

做这个的最好方式是什么?

谢谢你的帮助.

Ada*_*ski 9

您应该使用SwingWorker在后台线程上调用Python进程.这样,在长时间运行的任务运行时,您的UI将保持响应.

// Define Action.
Action action = new AbstractAction("Do It") {
  public void actionPerformed(ActionEvent e) {
    runBackgroundTask();
  }
}

// Install Action into JButton.
JButton btn = new JButton(action);

private void runBackgroundTask() {
  new SwingWorker<Void, Void>() {
    {
      // Disable action until task is complete to prevent concurrent tasks.
      action.setEnabled(false);
    }

    // Called on the Swing thread when background task completes.
    protected void done() {
      action.setEnabled(true);

      try {
        // No result but calling get() will propagate any exceptions onto Swing thread.
        get();
      } catch(Exception ex) {
        // Handle exception
      }
    }

    // Called on background thread
    protected Void doInBackground() throws Exception {
      // Add ProcessBuilder code here!
      return null; // No result so simply return null.
    }
  }.execute();
}
Run Code Online (Sandbox Code Playgroud)