java并发多线程问题demo求解答
public class DemoSafe {
private Integer val = new Integer(0);
public Integer getVal() {
synchronized (val) {
return val;
}
}
public void setVal(Integer val) {
synchronized (this.val) {
this.val = val;
}
System.out.println(Thread.currentThread().getName()+"set val:"+val);
}
public void setValAuto() {
synchronized (val) {
++this.val;
}
System.out.println(Thread.currentThread().getName()+"set val:"+val);
}
public static void main(String[] args) {
// final List<Demo> ls = Collections.synchronizedList(new ArrayList<Demo>());
// ls.add(new Demo());
/**
* Demo连续打印结果,发现最终结果并不是1000,说明是非线程安全的
* DemoSafe 打印的结果在980-1000之间,也是线程不安全?
* DemoSafe2 打印结果是1000,为线程安全对象
* **/
// final Demo d = ls.get(0);
final List<DemoSafe2> ls = Collections.synchronizedList(new ArrayList<DemoSafe2>());
ls.add(new DemoSafe2());
final DemoSafe2 d = ls.get(0);
for (int i = 0; i < 1000; i++) {
new Thread() {
public void run() {
d.setValAuto();
System.out.println(this.getName()+"get val:"+d.getVal());;
};
}.start();
}
try {
Thread.sleep(1000);
System.out.println("\n"+d.getVal());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
为什么,这个打印的最终结果不是1000?