6

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

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

所以这可能看起来像:

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
    }
}

这是最好的方法吗?

4

2 回答 2

4

是的,这是唯一的方法。

private synchronized myMethod() {
    // do work
}

相当于:

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

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

于 2015-01-14T21:41:58.497 回答
4

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

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

集合 API为线程安全提供了同步的包装器集合。

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

另一种方法是手动同步对列表的所有访问:

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

    ...

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

 }
于 2015-01-14T21:42:32.903 回答