【发布时间】:2016-03-15 21:52:58
【问题描述】:
我想看看volatile 在这里是如何工作的。如果我将cc 声明为volatile,我会得到下面的输出。我知道线程执行输出不时变化,但我在某处读到volatile 与synchronized 相同,那么为什么我会得到这个输出?如果我使用两个 Thread1 实例,这有关系吗?
public class Volexample {
int cc=0;
public static void main(String[] args) {
Volexample ve=new Volexample();
CountClass count =ve.new CountClass();
Thread1 t1=ve.new Thread1(count);
Thread2 t2=ve.new Thread2(count);
t1.start();
t2.start();
}
class Thread1 extends Thread{
CountClass count =new CountClass();
Thread1(CountClass count ){
this.count=count;
}
@Override
public void run() {
/*for(int i=0;i<=5;i++)
count.countUp();*/
for(int i=0;i<=5;i++){
cc++;
System.out.println(cc + Thread.currentThread().getName());
}
}
}
class Thread2 extends Thread {
CountClass count =new CountClass();
Thread2(CountClass count ){
this.count=count;
}
@Override
public void run(){
/*for(int i=0;i<=5;i++)
count.countUp();*/
for(int i=0;i<=5;i++){
cc++;
System.out.println(cc + Thread.currentThread().getName());
}
}
}
class CountClass{
volatile int count=0;
void countUp(){
count++;
System.out.println(count + Thread.currentThread().getName());
}
}
}
【问题讨论】:
-
volatile与synchronized不同:volatile提供内存可见性,但不提供原子性;synchronized两者都有。 -
你期望什么输出?为什么对
count.countUp()的调用被注释掉了?您如何访问 volatile 变量? -
o/p 是什么意思?
-
volatile 确实使
count++原子化。如果将其更改为 AtomicInteger,它将是原子的而不使用同步。 -
感谢您的即时响应,但我仍然有些困惑...... 1.正如我之前发布的那样,我在该类中有一个数据成员 cc,我有 2 个差异线程类 Thread1 和 Thread2 所以如果我使该数据成员 cc 易失,然后如您所见,上面的输出(o / p) 2 diff 线程已产生输出:: 2Thread-0 2Thread-1 因此,如果 volatile 反映主内存中的更改而不是线程内存中的更改,那么这怎么可能?2。如果我使用同一类 Thread1 类的 2 个不同线程,或者如果我使用 2 个 diff 线程类的 2 个线程(如 Thread1 和 Thread 2)之间是否存在差异?
标签: java multithreading synchronized volatile java-memory-model