【问题标题】:Signal one Java process from another从另一个 Java 进程发出信号
【发布时间】:2013-02-02 23:47:25
【问题描述】:

我需要从另一个 java 进程向一个 java 进程发送唤醒信号。我可以使用信号吗?我试图在互联网上找到一些东西,但找不到。谁能帮忙。

【问题讨论】:

  • 流程之间有什么关系?他们在同一台服务器上吗?他们在同一个网络上吗?它们在同一个 JVM 中吗?
  • @jgm ,你让我感兴趣,他们怎么可能在同一个 JVM 中?
  • @jgm 是的,它们在同一个 JVM 中..
  • 两个进程甚至可以共享同一个JVM吗?谁能提供参考?

标签: java


【解决方案1】:

假设您的意思是两个 java 线程,最简单的方法可能是使用 java 的等待/通知机制。你可以在 javadoc 中阅读更多关于它是如何工作的:http://docs.oracle.com/javase/7/docs/api/

这是一个演示其工作原理的示例程序。它会在每个线程运行时交替打印线程 ID。

public class Main {

  public static void main(String[] args) {
    final Object notifier = new Object();                       //the notifying object
    final long endingTime = System.currentTimeMillis() + 1000;  //finish in 1 s

    Runnable printThread = new Runnable(){
      @Override
      public void run() {
        synchronized (notifier){
          while(System.currentTimeMillis() < endingTime){
            try {
              notifier.wait();
              System.out.println(Thread.currentThread().getId());
              notifier.notify();  //notifies the other thread to stop waiting
            } catch (InterruptedException e) {
              e.printStackTrace();  //uh-oh
            }
          }
        }
      }
    };

    //start two threads
    Thread t1 = new Thread(printThread);
    Thread t2 = new Thread(printThread);
    t1.start();
    t2.start();

    //notify one of the threads to print itself
    synchronized (notifier){
      notifier.notify();
    }

    //wait for the threads to finish
    try {
      t1.join();
      t2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();  //uh-oh
    }
    System.out.println("done");
  }
}

【讨论】:

    【解决方案2】:

    我对同一 JVM 部分中的两个进程感到困惑(两个类加载器?)。无论哪种方式,最简单的方法是通过共享的本地套接字或文件进行通信。

    您甚至可以查看共享内存映射。

    【讨论】:

      【解决方案3】:

      取决于线程的相关程度。如果它们是相关的,那么像this previous question 的答案之一中建议的等待/通知设置就可以解决问题。

      如果你有更多的发布/订阅方法,那么我推荐 Guava 的 EventBus 作为线程间通信的简单方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 2013-02-17
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多