在 Java 中使用 synchronized (Thread.currentThread()){...} 的目的是什么? [英] What is the purpose of using synchronized (Thread.currentThread()){...} in Java?

查看:34
本文介绍了在 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()){...} 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆