public class Test {
private int i = 0;
public Test() {
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public static void main(String[] args) throws InterruptedException {
Test t = new Test();
Thread tt1 = new Thread(new TestThread(t));
Thread tt2 = new Thread(new TestThread(t));
Thread tt3 = new Thread(new TestThread(t));
Thread tt4 = new Thread(new TestThread(t));
tt1.start();
tt2.start();
tt3.start();
tt4.start();
tt1.join();
tt2.join();
tt3.join();
tt4.join();
System.out.println("ok");
}
}
public class TestThread implements Runnable {
Test t;
public TestThread (Test t) {
this.t = t;
}
public synchronized void run() {
t.setI(t.getI() + 10);
System.out.println(t.getI());
}
}
输出:
30
30
40
40
ok
问题 :
想要得到输出10 20 30 40,为什么加了synchronized还不行