打印出来的结果是-20000000
,证明我不需要同步size()
方法。但我的理解是我也应该同步size()
。这里的真实情况是什么?
public class Test {
public static void main(String[] args){
Counter c = new Counter();
T1 t1 = new T1(c);
T1 t2 = new T1(c);
t1.start();
t2.start();
try{
t1.join();
t2.join();
} catch (Throwable t) {
}
System.out.println("c=" + c.size());
}
}
class T1 extends Thread{
private Counter c;
public T1(Counter c){
this.c = c;
}
public void run(){
for(int i=0; i<10000000; i++){
c.decrement();
}
}
}
class Counter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public int size() {
return c;
}
}