【发布时间】:2017-08-14 16:02:54
【问题描述】:
我执行了下面的一段代码,期望计数为 20000。我已将计数声明为 volatile,但输出始终不正确。
package threading;
public class Demo5 {
private volatile int count =0;
public static void main(String[] args){
Demo5 d = new Demo5();
d.doWork();
}
public void doWork(){
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i=0; i<10000; i++){
count++;
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for(int i=0; i<10000; i++){
count++;
}
}
});
t1.start();
t2.start();
try{
t1.join();
t2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count+" is count");
}
}
后来我尝试通过将它放在同步方法中来将计数设为同步,并且它工作正常。
public synchronized void increment(){
count++;
}
有人能告诉我什么时候应该使用 volatile 以及什么时候应该使用 synchronized 吗?
【问题讨论】:
-
方法
count()是做什么的? -
这是错字。已更正。
标签: java multithreading synchronization volatile