java使用synchronized关键字的等待通知方法

标签 java multithreading wait synchronized notify

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

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

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 中发生,并且您需要访问对象实例来等待,因此 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 .

关于java使用synchronized关键字的等待通知方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426017/

相关文章:

检查两个进程的退出代码

javascript - Discord.js 在编辑消息之前发送并等待

java - 在锁定对象上调用 wait() 之前调用 notify() 可以吗?

java - 无法正确设置文本

java - 如何使用 spring mvc 3.0 注册处理程序拦截器?

java - 文件 I/O java 绝对文件名与相对文件名

java - 使用 Kotlin 在 android 中声明 UI 组件的最佳方法是什么?

java - 并发和异常

c++ - 对自己的互斥锁类使用lock_guard

android - Kotlin 高阶函数传递一个参数数量可变的函数作为参数