donghuige 2017-05-22 01:57 采纳率: 0%
浏览 386

java wait学习中遇到的疑问

为什么把同步监视对象换成线程对象**t**,main线程就可以自动唤醒,而自定义的对象main线程状态就一直是wait呢

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 21:51
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在Java中,线程是通过调用start()方法来开始执行的。当一个线程开始执行时,它会进入可运行状态(RUNNABLE),这意味着它可以被其他线程所调度。

    然而,如果一个线程处于等待状态(例如因为一个锁或者条件变量),那么它不会直接进入可运行状态。在这种情况下,你可以使用wait()notify()等方法来让这个线程从等待状态变为可运行状态。具体来说:

    • wait(): 如果当前线程正处于等待状态,则它会被阻塞直到有其他线程调用notify()wait()

      public class JoinTest {
          private boolean flag;
      
          public void run() {
              while (!flag) {
                  try {
                      System.out.println("waiting");
                      // do nothing.
                  } finally {
                      System.out.println("done waiting");
                      flag = true; // notify other threads to wake up this one
                  }
              }
          }
      }
      
    • notify():如果当前线程正处于等待状态,并且有其他线程调用了wait(),那么它将被唤醒并继续执行。

      public class JoinTest {
          private boolean flag;
      
          public void run() {
              synchronized(this) {
                  while (!flag) {
                      try {
                          System.out.println("waiting");
                          // do nothing.
                      } finally {
                          System.out.println("done waiting");
                          notifyAll();
                          flag = true; // notify other threads to wake up this one
                      }
                  }
              }
          }
      }
      
    • notifyAll():唤醒所有等待的线程。

      public class JoinTest {
          private boolean flag;
      
          public void run() {
              synchronized(this) {
                  while (!flag) {
                      try {
                          System.out.println("waiting");
                          // do nothing.
                      } finally {
                          System.out.println("done waiting");
                          notifyAll();
                          flag = true; // notify other threads to wake up this one
                      }
                  }
              }
          }
      }
      

    总结一下,如果你想要让某个线程从等待状态变为可运行状态,你需要先让它进入等待状态,然后在合适的时候通知它。这样做的目的是为了确保多个线程之间的同步和协作,从而实现并发编程的需求。

    评论

报告相同问题?