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

查看:1011
本文介绍了在Java中使用synchronized(Thread.currentThread()){...}的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的项目中遇到了以下代码:

I faced the following code in our project:

synchronized (Thread.currentThread()){
    //some code
}

我不明白在<$上使用synchronized的原因c $ c> 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) 。是真的吗?

推荐答案

考虑这个

    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天全站免登陆