用于启动进程并在进程

时间:2016-09-22 01:09:01

标签: java events callback

我的要求是从java启动一个进程并注册进程的事件回调,例如:like或killed。

典型情况:

在我的GUI应用程序中,我有一个“启动/运行”状态文本的“启动过程”按钮。我希望状态在进程运行或未运行时动态更改。 我不想连续检查进程列表和查询进程,但是在进程完成时会触发回调。

3 个答案:

答案 0 :(得分:0)

你可以尝试类似的东西:

public interface Callback{
    public void executeCallbackActions();
}

public static void main(String[] args) {
    Callback callback = new Callback() {

        @Override
        public void executeCallbackActions() {
            System.out.println("Who pressed the button?");
        }
    };

    runGui(callback);
}

public static void runGui(Callback callback){
    //When button is pressed
    callback.executeCallbackActions();
}

答案 1 :(得分:0)

快速和未经定义的解决方案 - Java8 - (以防万一:不知道:请参阅java.lang.Processjava.lang.ProcessBuilder了解如何启动)

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class ProcessObserver
implements Runnable {
  protected Consumer<Process> callback;
  protected Process           toExecute;


  public ProcessObserver(
    Consumer<Process> callback, 
    Process toExecute
  ) {
    super();
    this.callback = callback;
    this.toExecute = toExecute;
  }

  @Override
  public void run() {
    while(this.toExecute.isAlive()) {
      try {
        this.toExecute.waitFor(250, TimeUnit.MILLISECONDS);
      } catch (InterruptedException e) {
        this.toExecute.destroyForcibly();
        return; // Honouring the interrupt request,
                // bail out here and don call the callback
      }
    }
    this.callback.accept(this.toExecute);
  }

  static public void main(String[] args) {
    ThreadPoolExecutor pool=new ThreadPoolExecutor(
        4, 1024, // the threads will mostly sleep in waitFors
        3600, TimeUnit.SECONDS, 
        new LinkedBlockingQueue<Runnable>()
    );

    Process longRunningProcess=null; // initialize it properly
    ProcessObserver observer=new ProcessObserver(
      (Process p)->System.out.println("Exit code of: "+p.exitValue()),
      longRunningProcess
    );
    pool.execute(observer);
  }
}

更精确的解决方案将涉及监视多个进程的单个线程周期性地轮询它们并为退出的那些调用相关的回调(毕竟,报告长时间运行的进程的退出代码的延迟时间为0.2s-1秒)。这太过分了。)

答案 2 :(得分:0)

你可以使用如下的processbuilder

public class ProcessBuildDemo {
   public static void processdone() {
        System.out.println("processing is done....");
    }
    public static void main(String[] args) throws IOException {  
       String[] command = {"notepad.exe"};
        ProcessBuilder probuilder = new ProcessBuilder( command );
        Process process = probuilder.start();
        // 
        // set status of you button as process is runnning

        //Read out dir output
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running %s is:\n",
                Arrays.toString(command));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //Wait to get exit value
        try {
            int exitValue = process.waitFor();
          //set status of you button as process is stop or do call function
            processdone();                  
            System.out.println("\n\nExit Value is " + exitValue);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}