【发布时间】:2014-06-19 17:35:23
【问题描述】:
我正在学习 volatile 变量。我知道 volatile 的作用,我为 Volatile 变量编写了一个示例程序,但没有按预期工作。
为什么程序会无限循环? 如果变量“isTrue”是易失的,那么它应该总是从主内存中获取值吗?为什么线程要缓存它?
有人能解释一下原因吗?以及是否可以提供解决方案...(我不会将 isTrue 放入 while 循环)
我有一个 VolatileSample 类:-
public class VolatileSample{
static volatile boolean isTrue=true;
public VolatileSample(boolean is){
isTrue=is;
}
public void print() {
boolean b=isTrue;
while (b) {
System.out.println("In loop!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setFalse() {
boolean b=false;
System.out.println("Setting value as false");
isTrue=b;
}
}
创建了两个线程:-
public class Thread1 extends Thread{
VolatileSample sample;
public Thread1(VolatileSample sample){
this.sample=sample;
}
public void run(){
sample.print();
}
} 和
public class Thread2 extends Thread{
VolatileSample sample;
public Thread2(VolatileSample sample){
this.sample=sample;
}
public void run(){
sample.setFalse();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
主类:-
public class Test {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
VolatileSample sample=new VolatileSample(true);
Thread1 t1=new Thread1(sample);
Thread2 t2=new Thread2(sample);
t1.start();
t2.start();
}
}
【问题讨论】:
-
你能解释一下为什么你不想使用 while(isTrue) 吗?
标签: java multithreading volatile