【发布时间】:2012-11-14 10:08:11
【问题描述】:
这里我有三个简单的类:
第 1 类:
public class ThreadSyncMain {
public static int count = 0; // volatile is not use
public static void main(String[] args) {
Thread thread1 = new Thread( new Thread1(),"Thread1" );
Thread thread2 = new Thread( new Thread2(),"Thread2");
thread1.start();
thread2.start();
}
}
第 2 类:
public class Thread1 implements Runnable{
public void run() {
System.out.println("Thread1 Count :: "+ThreadSyncMain.count);
ThreadSyncMain.count++;
}
}
第 3 类:
public class Thread2 implements Runnable{
public void run() {
System.out.println("Thread2 Count :: "+ThreadSyncMain.count);
}
}
输出是:
线程 1 计数 :: 0
线程 2 计数 :: 1
这意味着thread1改变了count的值。那么为什么 thread1 的变化会影响 thread2,因为我没有使用任何“volatile”关键字。在这种情况下,“volatile”关键字不是问题吗?如何修改代码以测试“volatile”?
提前致谢。
更新部分: 在进行了一些命中和试用测试后,我正在更新代码。 1 类保持不变。这是更新的代码:
第 2 类:我添加了 100 毫秒的延迟。
public class Thread1 implements Runnable{
public void run() {
System.out.println("Thread1 Count :: "+ThreadSyncMain.count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ThreadSyncMain.count++;
}
}
第 3 类:添加了 while 循环。它里面的计数被持续监控。
public class Thread2 implements Runnable{
public void run() {
while(true)
{
if(ThreadSyncMain.count == 1)
{
System.out.println("Thread2 Count :: "+ThreadSyncMain.count);
}
}
}
}
现在在这种情况下,我得到了以下输出:
1.如果class1中没有使用“volatile”,输出为:
Thread1 Count :: 0
2。如果在 class1 中使用“volatile”,则输出为:
Thread1 Count :: 0
Thread2 Count :: 1
Thread2 Count :: 1
Thread2 Count :: 1
.
.
.
为什么 volatile 在这种情况下会出现?
【问题讨论】:
标签: java multithreading unit-testing