java - 为什么在主线程实例的对象上加锁有效?
问题描述
在下面的代码中,我对 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
解决方案
- 不。
- 无关紧要。此代码中没有任何通知 - 没有人
notify(All)
在其中的任何地方调用。 - 因为
Thread.sleep(15000)
也会这样做,这实际上是你的wait
电话所做的,因为没有人通知。
推荐阅读
- python - 仅在使用 selenium 刮擦时添加到 DF 的最后刮擦项目
- flutter - 如何在 Flutter 的 Stack 中移除 Widget 的内边框?
- java - Android Studio 看不到 MainActivity
- angular - 使用 Jasmine 进行 Angular 单元测试 - 错误:请添加 @NgModule 注释
- javascript - 如何使用 javascript 将 html 文本包装成 span
- python - .replace() 应用于 pandas 中的多个列时不起作用
- r - 出了点问题;缺少所有准确度指标值:
- sql - 在 SQL 中的表或视图上添加索引
- html - 视频宽度修复和视频上的文本定位以及使文本移动响应
- file - 较大缓冲区的 C write() 吞吐量不一致