我已经阅读了很多关于线程的文章,但我不确定处理这种情况的正确方法。假设我有一个引用对象的实用程序类。实用程序类确实在对象上工作,并且可以从多个线程调用
class Utility{
Foo xx;
public Utility(Foo xx){
this.xx = xx;
}
public void doWork(){
x.action();
}
}
现在,如果我有两个线程将访问实用程序类并调用 doWork(),其中 xx 将始终引用同一个对象,我如何才能使其成为线程安全的?
编辑:实用程序类有 2 个实例(每个线程一个)但引用的 xx 对象相同。见编辑:
public class ThreadSafety {
public static void main(String[] args) throws InterruptedException {
Foo xx = new Foo();
Utility util1 = new Utility(xx);
Utility util2 = new Utility(xx);
Thread t1 = new Thread(new MyRunnable(util1) , "t1");
Thread t2 = new Thread(new MyRunnable(util2) , "t2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}
class MyRunnable implements Runnable{
Utility util;
@Override
public void run() {
util.doWork();
}
private void MyRunnable (Utility util) {
this.util = util;
}
}
最佳答案
public class Utility{
private final Foo xx;
public Utility(Foo xx){
this.xx = xx;
}
public void doWork() {
// ensures only one thread can be calling action
synchronized(xx) {
xx.action();
}
}
}
下面的一些变化:
- 使
xx
final
和private
。将其设置为private
可强制控制如何访问xx
。
在调用 同步
。您可以将synchronized
放在方法声明中,但我更愿意明确说明您锁定的对象。请注意,这不会“同步 xx”。它只是使用xx
作为锁。在访问潜在危险代码块的任何地方,都必须使用具有相同监视器对象的同步块(synchronized block)。
doWork
之前在 xx
上关于java - 如何使这个线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436239/