【发布时间】:2016-04-06 09:08:09
【问题描述】:
在我的项目中,我必须使用一个类X,它提供了很多方法,但是文档没有提到这些方法是否是线程安全的,而且我也没有源代码。
所以我用互斥锁将X 封装在另一个类中:
public class MyX {
private X instance;
public final Object mutex = new Object();
public MyX () {
this.instance = new X();
}
public X getMethods () {
return this.instance;
}
}
当我需要调用X 的方法时,我使用synchronized 块:
MyX myX = new MyX();
synchronized (myX.mutex) {
X methods = myX.getMethods();
methods.method1();
methods.method2();
... ... ...
}
或者,也许我可以直接在 X 类的实例上进行同步:
X instance = new X();
synchronized(instance) {
instance.method1();
instance.method2();
... ... ...
}
我想知道走哪条路更好,有没有更好的设计来解决这个问题。
谢谢。
【问题讨论】:
标签: java multithreading synchronization synchronized thread-synchronization