关于synchronized不能锁定i++的疑问
在验证i++是不是原子性的过程中,发现用synchronized仍不能使方法同步。请问这是为什么?还有改如何修改才能使结果为0?
代码如下:
public class TestI implements Runnable{
public boolean flag;
public volatile static Integer i = 0;
private int n1 =0;
public void run(){
while(flag==true&&n1<100000){
synchronized(this){
i++;
++n1;
}
}
while(flag==false&&n1<100000){
synchronized(this){
i--;
++n1;
}
}
}
public static void main(String[] args){
TestI t = new TestI();
Thread t1 = new Thread(t);
TestI tt = new TestI();
tt.flag = true;
Thread t2 = new Thread(tt);
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){};
System.out.println(t.i);
}