同步 Java 中的对象

Synchronizing on an object in Java

我正在寻找类似于此语法的东西,尽管它不存在。

我想让一个方法作用于一个集合,并且在该方法的生命周期内,确保集合没有被弄乱。

所以它看起来像:

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
}

但是,恐怕唯一的方法是:

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

这是最好的方法吗?

是的,这是唯一方式。

private synchronized myMethod() {
    // do work
}

相当于:

private myMethod() {
    synchronized(this) {
         // do work
    }
}

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

这种情况最好使用同步列表:

List<X> list = Collections.synchronizedList(new ArrayList<X>());

集合 API 提供 synchronized wrapper collections 线程安全。

同步方法主体中的列表将阻塞需要在方法的整个生命周期内访问该列表的其他线程。

替代方法是手动同步对列表的所有访问:

private void doSomethingWithTheCollectionX(List<?> collectionX){
    ...
    synchronized(collectionX) {
       ... e.g. adding to the list
    }

    ...

    synchronized(collectionX) {
       ... e.g. updating an element
    }

 }