首页 > 解决方案 > 为什么在主线程实例的对象上加锁有效?

问题描述

在下面的代码中,我对 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");
    }
}

  1. 当他们完成执行时执行并mn调用portnotify()
  2. 收到通知的监视器是谁?(由于main()是静态的,因此其中的代码main()不绑定到特定对象。)
  3. 为什么在主线程实例的对象上加锁(即,将通知发送到,因为它是静态的thisInstance,所以没有绑定)。是不是因为所有对象都被通知了,因为它们都在一个静态方法中,因此与每个实例相关联?main()main()TestThreads3LambdaWaitmnport

标签: javamultithreadingwaitsynchronizednotify

解决方案


  1. 不。
  2. 无关紧要。此代码中没有任何通知 - 没有人notify(All)在其中的任何地方调用。
  3. 因为Thread.sleep(15000)也会这样做,这实际上是你的wait电话所做的,因为没有人通知。

推荐阅读