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

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

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

  1. /*
  2. * Taken from
  3. * https://www.wiley.com/en-us/Java+Programming%3A+24+Hour+Trainer%2C+2nd+Edition-p-9781118951453
  4. */
  5. public class TestThreads3LambdaWait {
  6. public static void main(String args[]){
  7. // Lambda expression for Market News
  8. Runnable mn = () -> {
  9. try{
  10. for (int i=0; i<10;i++){
  11. Thread.sleep (1000); // sleep for 1 second
  12. System.out.println( "The market is improving " + i);
  13. }
  14. }catch(InterruptedException e ){
  15. System.out.println(Thread.currentThread().getName()
  16. + e.toString());
  17. }
  18. };
  19. Thread marketNews = new Thread(mn, "Market News");
  20. marketNews.start();
  21. // Lambda expression for Portfolio
  22. Runnable port = () ->{
  23. try{
  24. for (int i=0; i<10;i++){
  25. Thread.sleep (700); // Sleep for 700 milliseconds
  26. System.out.println( "You have " + (500 + i) +
  27. " shares of IBM");
  28. }
  29. }catch(InterruptedException e ){
  30. System.out.println(Thread.currentThread().getName()
  31. + e.toString());
  32. }
  33. };
  34. Thread portfolio = new Thread(port,"Portfolio data");
  35. portfolio.start();
  36. TestThreads3LambdaWait thisInstance = new TestThreads3LambdaWait();
  37. synchronized (thisInstance) {
  38. try{
  39. thisInstance.wait(15000);
  40. System.out.println("finished wait");
  41. } catch (InterruptedException e){
  42. e.printStackTrace();
  43. }
  44. }
  45. System.out.println( "The main method of TestThreads3Lambda is finished");
  46. }
  47. }

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

u4vypkhs

u4vypkhs1#

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

相关问题