同步TreeSet演员?

时间:2016-01-24 19:42:42

标签: java collections synchronization treeset

我在Java中使用TreeSet来保存整数列表:

TreeSet<Integer> num = new TreeSet<Integer>();

由于我的应用程序有多个线程,我希望能够同步访问 。我正在使用Collections.synchronizedSortedSet(num);,这会返回Collections$SortedSet。我的问题是,这不能转换为TreeSet - 它只能转换为SortedSet。我无法更改num对象的类,因此必须转换为TreeSet

是否有人知道我如何以Collections$SortedSet方式投放TreeSet或我可以同步此TreeSet的其他方法?

1 个答案:

答案 0 :(得分:2)

没有这样的实现,但你可以轻松地让你的一个。只需扩展TreeSet,并使用同步方法覆盖它的方法。

例如:

public class MySyncedTreeSet extends TreeSet {
    @Override
    public synchronized boolean isEmpty() {
        return super.isEmpty();
    }

    @Override
    public synchronized boolean contains(Object o) {
        return super.contains(o);
    }

    // and the same for all other methods
}