【发布时间】:2013-01-12 06:01:04
【问题描述】:
我有两个线程。第一个线程调用 setX 方法,第二个线程调用 getX 方法。尽管我只有一个写作线程,但我是否必须将方法设置为同步?我也可以用第二个类和 volatile 变量来解决我的线程问题吗?
public class Test {
private int x;
public synchronized void setX(int x) {
this.x = x;
}
public synchronized int getX() {
return this.x;
}
}
public class Test2 {
private volatile int x;
public void setX(int x) {
this.x = x;
}
public int getX() {
return this.x;
}
}
【问题讨论】:
标签: java multithreading synchronized volatile