如何在不使用Collections Class方法的情况下使集合类同步?还有其他课吗?或者我可以覆盖ArrayList类的方法然后使其同步吗?
答案 0 :(得分:1)
要同步任何对象,可以使用处理同步的调用处理程序,并在要同步的对象上创建代理。例如:
public static class Synchronizer implements InvocationHandler{
private final Object objectToSync;
public Synchronizer(Object objectToSync){
this.objectToSync = objectToSync;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
synchronized (objectToSync){
return method.invoke(objectToSync, args);
}
}
}
public static void main(String ... args) {
List<Integer> originalList = new ArrayList<>();
List<Integer> syncList = (List<Integer>) Proxy.newProxyInstance(Synchronizer.class.getClassLoader(), new Class[]{List.class}, new Synchronizer(originalList));
}