What is the purpose of using synchronized (Thread.currentThread()){...} in Java?(在 Java 中使用 synchronized (Thread.currentThread()){...} 的目的是什么?)
问题描述
我在我们的项目中遇到了以下代码:
I faced the following code in our project:
synchronized (Thread.currentThread()){
//some code
}
我不明白在 currentThread
上使用同步的原因.
I don't understand the reason to use synchronized on currentThread
.
有什么区别
synchronized (Thread.currentThread()){
//some code
}
只是
//some code
你能举个例子说明区别吗?
Can you provide an example which shows the difference?
更详细的这段代码如下:
more in details this code as follows:
synchronized (Thread.currentThread()) {
Thread.currentThread().wait(timeInterval);
}
看起来只是 Thread.sleep(timeInterval)
.是真的吗?
It looks like just Thread.sleep(timeInterval)
. Is it truth?
推荐答案
考虑一下
Thread t = new Thread() {
public void run() { // A
synchronized (Thread.currentThread()) {
System.out.println("A");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
};
t.start();
synchronized (t) { // B
System.out.println("B");
Thread.sleep(5000);
}
块 A 和 B 不能同时运行,因此在给定的测试中,A"或B"输出将延迟 5 秒,哪个先出现是未定义的
blocks A and B cannot run simultaneously, so in the given test either "A" or "B" output will be delayed by 5 secs, which one will come first is undefined
这篇关于在 Java 中使用 synchronized (Thread.currentThread()){...} 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中使用 synchronized (Thread.currentThread()){...} 的目的是什么?


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01