在 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

相关文章