如果正在运行任何其他java程序,则监听Java程序

时间:2018-05-30 08:47:33

标签: java

我有两个java程序: Demo1.java Demo2.java

Demo2.java

public class Demo2 extends Thread{
  public void run(){
    while(true){
     System.out.println("Demo2 is running");
    }
  }
}

我想:

  1. 运行Demo2
  2. 当Demo2正在运行时运行Demo1
  3. 从Demo1中了解Demo2是否正在运行。
  4. 我该如何撰写 Demo1.java

1 个答案:

答案 0 :(得分:0)

如果我理解,你有两个程序意味着两个分离的线程。因此,您可以像这样访问进程列表:

视窗:

try {
    Process proc = Runtime.getRuntime().exec("process.exe");
    BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
    oStream.write("process where name='process.exe'");
    String line;
    while ((line = input.readLine()) != null) { 
        if (line.contains("process.exe")) 
            return true; 
    } 
    input.close(); 
} 
catch (Exception ex) { 
    // handle error 
}

Linux的:

try {
    Process p = Runtime.getRuntime().exec(new String[] { "bash", "-c", "ps aux | grep process" });
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
        if (line.contains("process")) {
            // process is running
        }
    }
}
catch (Exception e) {
    // handle error
}

希望它有所帮助。