日期:2014-05-20 浏览次数:20739 次
package org.volatiles;
import java.io.IOException;
import java.util.Properties;
/**
* volatile禁止指令重排序优化
*
* @author Byron
*
*/
public class VolatileTest2 {
boolean initialized = false;
String name;
String age;
String sex;
public static void main(String[] args) {
VolatileTest2 test = new VolatileTest2();
test.start();
}
public void start() {
Thread t1 = new Thread(new GetProperties());
Thread t2 = new Thread(new UseProperties());
t1.start();
t2.start();
}
/**
* 获取文件中的属性信息
* @author Byron
*
*/
class GetProperties implements Runnable {
@Override
public void run() {
Properties p = new Properties();
try {
p.load(getClass().getResourceAsStream("test.properties"));
name = p.getProperty("name");
age = p.getProperty("age");
sex = p.getProperty("sex");
initialized = true;// 实验了无数次还是没有出现重排序
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读取GetProperties从文件中取出的信息
* @author Byron
*
*/
class UseProperties implements Runnable {
@Override
public void run() {
while (!initialized) {
// wait
// System.out.println("wait 1 ms");
}
System.out.println("name is: " + name);
System.out.println("age is: " + age);
System.out.println("sex is: " + sex);
}
}
}