简体   繁体   English

具有独立共享变量的同步方法

[英]Synchronized methods with independent shared variables

I recently asked about if synchronized methods in Java shared the same lock key.我最近询问了 Java 中的同步方法是否共享相同的锁定密钥。 The answer was yes.答案是肯定的。 But the next thought I had was that this pattern is very restrictive and can cause unnecessary delays.但我的下一个想法是,这种模式非常严格,可能会导致不必要的延迟。 For example suppose we have 2 synchronized methods and each of them process different and independent shared variables.例如,假设我们有 2 个同步方法,每个方法处理不同且独立的共享变量。 What's the point of locking both methods at the same time if the processing of one variable does not affects the other?如果一个变量的处理不影响另一个变量,那么同时锁定这两种方法有什么意义? Is there a way to deal with this situation?有没有办法处理这种情况?

Suppose you have this class:假设你有这个 class:

class C {
    public synchronized void foo(...) { ... }
    public synchronized void bar(...) { ... }
    ...
}

And suppose you have:假设你有:

final C c_0 = new C(...);
final C c_1 = new C(...);

The fact that foo() and bar() both are synchronized does not prevent one thread from calling c_0.foo(...) while another thread simultaneously calls c_1.bar(...) . foo()bar()都是synchronized的这一事实并不能阻止一个线程调用c_0.foo(...)而另一个线程同时调用c_1.bar(...) In fact, it does not even prevent one thread from calling c_0.foo(...) while another thread calls c_1.foo(...) .事实上,它甚至不会阻止一个线程调用c_0.foo(...)而另一个线程调用c_1.foo(...)

A so-called "synchronized method"所谓的“同步方法”

synchronized void foo(...) { ... }

Really is just syntactic sugar for this:真的只是语法糖:

void foo( ... ) {
    synchronized(this) {
        ...
    }
}

So, if one thread calls c_0.foo() it's "synchronizing" on the c_0 instance, and if another thread calls c_1.foo() , that thread is synchronizing on the c_1 instance--a different instance.因此,如果一个线程调用c_0.foo()它在c_0实例上“同步”,如果另一个线程调用c_1.foo() ,则该线程正在c_1实例上同步 - 一个不同的实例。

The synchronized keyword on the foo and bar methods only matters if two different threads both try to operate on the same instance at the same time. foobar方法上的synchronized关键字仅在两个不同的线程都尝试同时在同一个实例上操作时才重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM