java - 如果线程之间没有 Java 中的公共(public)数据,如何指定线程之间的通知

标签 java multithreading

我有一个 Java 线程,它启动 HttpService

ProcessBuilder pb = new ProceeBuilder(command);
Process process = pb.start();
process.waitFor();

我有另一个线程来检查服务是否已启动。

while (result != 0) {
  ServerSocket socket = new ServerSocker(port);
  socket.close();
  result = 0
  catch (BindException be) {
    result = 1;
  }
}

现在我需要以某种方式获取有关服务是否启动失败或成功启动的信息。我需要将其返回到启动这两个线程的主类才能继续。类似的东西

while (!started || !failed) {
     wait for getting information from the threads.
}

你有什么建议? 谢谢。

最佳答案

使用传递给两个线程的回调怎么样?

(省略 try catch )

public class MyCallback {
  private Boolean processSuccess;
  private Boolean serviceSuccess;
  public synchronized void notifyProcessStart(boolean success) {
    this.processSuccess = success;
    this.notifyAll();
  }
  public synchronized void notifyServiceCheck(boolean success) {
    this.serviceSuccess = success;
    this.notifyAll();
  }
  public synchronized void waitForResult() {
    while(processSuccess == null || serviceSuccess == null) {
      this.wait();
    }
    // ... do something good
  }
}

关于java - 如果线程之间没有 Java 中的公共(public)数据,如何指定线程之间的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4240108/

相关文章:

java - 来自数据库的 jfreechart 散点图

java - 高效的线程方案

c++ - 构造线程执行派生类的成员函数

java - 为什么使用parallelStream访问和修改Collection会得到不同的结果?

c# - 为什么值变量不改变?

java - 比较整数对象与 int

java - 为什么 64 位 JVM 比 32 位更快?

java - java中静态方法的线程安全

java - maven Surefire 插件 - 按顺序运行所有测试

java - 每次我尝试打开 eclipse 时都无法创建 java 虚拟机错误