Max*_*xii 5 java multithreading volatile synchronized
我有两个主题.第一个线程调用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;
}
}
Run Code Online (Sandbox Code Playgroud)
而不是使用synchronized 或 volatile在这里,我个人使用AtomicInteger:
public class Test {
private final AtomicInteger x = new AtomicInteger();
public void setX(int value) {
x.set(value);
}
public int getX() {
return x.get();
}
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我已经修复了你的get/ set- 以前你的getX设置,你setX得到了......)
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |