1

I need to send wakeup signal to a java process from another java process. Can I do it using signals? I tried to find some stuff on internet but couldnt get. Can anyone please help.

4

3 回答 3

1

I am confused on two process in same JVM part (Two class loaders ?). Either way, easiest way is to communicate over the shared local socket or a file.

You can even look at shared memory map.

于 2013-02-03T00:10:27.003 回答
1

假设您的意思是两个 java 线程,最简单的方法可能是使用 javas 等待/通知机制。您可以在 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");
  }
}
于 2013-02-03T00:29:45.620 回答
0

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

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

于 2013-02-03T00:00:16.360 回答