java 使用同步关键字等待通知方法

java wait notify methods using synchronized key word

我需要有人为我简化 java 中的等待通知方法。 我现在已经查看了大约 200 多个网站,但仍然不明白。

我正在开发一个程序,该程序需要让一个线程等待,直到从另一个线程调用 notify...

class mainClass{
 public static void main(String args[])throws Exception{
      Thread t1 = new Thread(new Runnable(){
           public void run(){
           //code inside to make thread t1 wait untill some other thread
           //calls notify on thread t1?
           }
      });
      t1.start();


      synchronized(t1){
           //main thread calling wait on thread t1?
           t1.wait();
      }



      new Thread(new Runnable(){
           public void run(){
                try{
                     synchronized(t1){
                          t1.notify() //?????
                     }
                }catch(Exception e1){}
           }
      }).start();
 }
}

等待需要发生在第一个 Runnable 中,您需要有权访问要等待的 Object 实例,因此 t1 Thread 实例将无法工作。在这段代码中,我创建了一个单独的锁对象。

public static void main(String[] args) {
    final Object lock = new Object();
    new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized(lock) {
                try {
                    lock.wait();
                    System.out.println("lock released");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    System.out.println("before sleep");
    try {
        Thread.sleep(1000);
        System.out.println("before notify");
        synchronized(lock) {
            lock.notify();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

使用线程通知可能很难测试。我建议使用基于消息的方法,例如 Akka.