这是我的测试代码
public class Test {
public static void main(String[] args) {
Data data = new Data();
Thread t1 = new Thread(new Print(data));
t1.setName("Print");
Thread t2 = new Thread(new Update(data));
t2.setName("Update");
t2.start();
t1.start();
}
private static class Data {
private String number = "0";
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
private static class Update implements Runnable {
private Data data;
public Update(Data data) {
this.data = data;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String number = String.valueOf(i);
data.setNumber(number);
if (number.equals("100000")) {
System.out.println("|" + System.currentTimeMillis() + "|");
break;
}
}
System.out.println("update finish");
}
}
private static class Print implements Runnable {
private Data data;
public Print(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
@Override
public void run() {
while (true) {
if (data.getNumber().equals("100000")) {
System.out.println("#" + System.currentTimeMillis() + "#");
break;
}
}
}
}}
我想更新已归档的数字,当等于100000时打印它。但是当我运行此代码时,Print任务被阻止,当我将数字定义为volatile时,它运行良好。我不明白为什么......,任何人都可以帮助我吗?