System.out.println(currentThreadName+" is running!");
Random random = new Random();
int age = random.nextInt(100);
System.out.println("thread "+currentThreadName +" set age to:"+age);
Student student = getStudent();
student.setAge(age);
System.out.println("thread "+currentThreadName+" first read age is:"+student.getAge());
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("thread "+currentThreadName +" second read age is:"+student.getAge());
}
protected Student getStudent() {
Student student = (Student)studentLocal.get();
if(student == null) {
student = new Student();
studentLocal.set(student);
}
return student;
}
protectedvoid setStudent(Student student) {
studentLocal.set(student);
}
}
运行程序后,屏幕输出: b is running! thread b set age to:0 thread b first read age is:0 a is running! thread a set age to:17 thread a first read age is:17 thread b second read age is:0 thread a second read age is:17