在Java中同步对象

Ale*_*lls 6 java thread-synchronization java-collections-api

我正在寻找类似于这种语法的东西,即使它不存在.

我希望有一个方法作用于集合,并且在方法的生命周期中,确保集合不会被搞乱.

这可能看起来像:

private void synchronized(collectionX) doSomethingWithCollectionX() {
    // do something with collection x here, method acquires and releases lock on
    // collectionX automatically before and after the method is called
}
Run Code Online (Sandbox Code Playgroud)

但相反,我担心这样做的唯一方法是:

private void doSomethingWithTheCollectionX(List<?> collectionX) {
    synchronized(collectionX) {
        // do something with collection x here
    }
}
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?

Jea*_*art 4

是的,这是唯一的方法。

private synchronized myMethod() {
    // do work
}
Run Code Online (Sandbox Code Playgroud)

相当于:

private myMethod() {
    synchronized(this) {
         // do work
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您想在除 之外的其他实例上同步this,您别无选择,只能synchronized在方法内声明该块。