为什么在主线程示例的对象上设置一个锁会起作用?

zqry0prt  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(316)

我对以下代码中的多线程和java等待有一些问题。

/*
 * Taken from
 * https://www.wiley.com/en-us/Java+Programming%3A+24+Hour+Trainer%2C+2nd+Edition-p-9781118951453
 */
public class TestThreads3LambdaWait {

  public static void main(String args[]){

    // Lambda expression for Market News
      Runnable mn = () -> {
         try{
          for (int i=0; i<10;i++){
           Thread.sleep (1000);  // sleep for 1 second
           System.out.println( "The market is improving " + i);
          } 
        }catch(InterruptedException e ){
           System.out.println(Thread.currentThread().getName() 
                                            + e.toString());
        }  
     }; 

     Thread marketNews = new Thread(mn, "Market News");
     marketNews.start();

    // Lambda expression for Portfolio
     Runnable port = () ->{
         try{
              for (int i=0; i<10;i++){
               Thread.sleep (700);    // Sleep for 700 milliseconds 
               System.out.println( "You have " +  (500 + i) +  
                                              " shares of IBM");
              }
            }catch(InterruptedException e ){
              System.out.println(Thread.currentThread().getName() 
                                                + e.toString());
            }   
     };

     Thread portfolio = new Thread(port,"Portfolio data");
     portfolio.start();

     TestThreads3LambdaWait thisInstance = new TestThreads3LambdaWait();

     synchronized (thisInstance) {
           try{
               thisInstance.wait(15000);
               System.out.println("finished wait");
           } catch (InterruptedException e){ 
               e.printStackTrace();
           }
         }
          System.out.println( "The main method of TestThreads3Lambda is finished");
  }
}

mn 以及 port 呼叫 notify() 他们什么时候执行完?
得到通知的班长是谁(自 main() 是静态的,代码在 main() 不绑定到特定对象。)
为什么在主线程示例的对象上放置一个锁会起作用(例如,将通知发送到 thisInstance ,这与 main()main() 是静态的)。是因为 TestThreads3LambdaWait 通知对象是因为 mn 以及 port 在静态方法中,因此绑定到每个示例?

u4vypkhs

u4vypkhs1#

不。
无关紧要。此代码中没有任何通知-没有人呼叫 notify(All) 在里面的任何地方。
因为 Thread.sleep(15000) 也会这样做,这实际上是 wait 如果没有人通知的话,我会打电话的。

相关问题