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()){...} 的目的是什么?
				
        
 
            
        - 如何指定 CORS 的响应标头? 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 
						
						
						
						
						
				
				
				
				