简体   繁体   English

可以在方法级别同步被Lock代替吗?

[英]can synchronized at method level be replaced by Lock?

When writing a thread safe class, we use synchronized keyword at two places in code, 在编写线程安全类时,我们在代码的两个位置使用了synchronized关键字,

1.Method level synchronization 1.方法级同步

2.Synchronized blocks 2.同步块

As far as I can think of, interfaces like Lock ( java.util.concurrent.locks.Lock )can be used in place of synchronized only at block level but not at method level. 就我所能想到的,像Lockjava.util.concurrent.locks.Lock )这样的接口只能在块级而不是方法级用于synchronized or is there a way? 还是有办法吗?

I don't have any real need of it but just curios since heard discussions that Lock can be a replacement for synchronized . 我不具备任何真正的需要,但杳无音讯的讨论,只是古董Lock可换货的synchronized

public class SampleClass {
    public synchronized void method(){
      .....
    }
}

There is no special syntax for "acquire the Lock at the beginning of the method, and release it at the end," like there is for synchronized . synchronized方法”没有特殊的语法“在方法的开头获取Lock,然后在最后释放它”。

You can, of course, just do that yourself: 当然,您可以自己做:

public void method() {
    lock.lock();
    try {
        // rest of the method
    } finally {
        lock.unlock();
    }
}

As we all know 众所周知

public class SampleClass {
    public synchronized void method(){
      .....
    }
}

and

public class SampleClass {
    public void method(){
        synchronized(this) {
           .....
        }
    }
}

is equivalent for all practical purposes. 对于所有实际目的都是等效的。

So you need to change method synchronization to equivalent block synchronization and the later can be replaced by Lock 因此,您需要将方法同步更改为等效的块同步,然后可以将其替换为Lock

No, there's no way to do this since java.util.concurrent —and therefore Lock or any other implementation as well—is just a library, whereas synchronized is part of the Java Language Specification . 不,没有办法做到这一点,因为java.util.concurrent因此Lock或任何其他实现)只是一个库,而synchronizedJava Language Specification的一部分

Regarding " Lock can be a replacement for synchronized", Brian Goetz discusses this in "Java Concurrency in Practice" in chapter 13.4: 关于“ Lock可以替代同步”,Brian Goetz在“ Java并发实践”第13.4章中对此进行了讨论:

ReentrantLock is an advanced tool for situations where intrinsic locking is not practical. ReentrantLock是用于内部锁定不实际的情况的高级工具。 Use it if you need its advanced features: timed, polled, or interruptible lock acquisition, fair queueing, or non-block-structured locking. 如果需要高级功能,请使用它:定时,轮询或可中断的锁获取,公平队列或非块结构锁。 Otherwise, prefer synchronized. 否则,建议同步。

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

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