import java.util.ArrayList;
public class ThreadTest {
public static void main(String[] args) {
ArrayList arr = new ArrayList();
for (int i =0; i<10 ; i++)
arr.add(new MyTh(i));
for (int i =0; i<10 ; i++) {
((Thread ) arr.get(i)).start();
}
}
}
class MyTh extends Thread {
int num;
volatile int age;
MyTh (int k)
{this.num=k; }
@Override
public void run() {
if(this.num==4){
setAge(40);
}
System.out.println(Thread.currentThread().getName() + " :"+this.num + ":" + getAge());
}
synchronized int getAge() {
return age;
}
synchronized void setAge(int k) {
this.age =k;
}
}
我在这里感到困惑,为什么程序的输出只打印一次volatile变量age = 40的值。我试图使两者在getter / setter中保持同步,然后也只有第4个单线程将其打印40。为什么其他后续线程也不能读取它40?
Thread-0 :0:0
Thread-1 :1:0
Thread-2 :2:0
Thread-3 :3:0
Thread-4 :4:40
Thread-5 :5:0
Thread-6 :6:0
Thread-7 :7:0
Thread-8 :8:0
Thread-9 :9:0
犯罪嫌疑人X
相关分类