以下代码发现输出结果不是从小到大的顺序,如何保证它按照从小到大的顺序?
Java代码
public class TestSync {
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread1()).start();
}
}
public int getNum(int i) {
synchronized (this) {
i++;
}
return i;
}
static class Thread1 implements Runnable {
static Integer value = 0;
@Override
public void run() {
TestSync ts = new TestSync();
value = ts.getNum(value);
System.out.println("thread1:" + value);
}
}
}
getNum
对于每个线程都只返回1...你从未实际修改过value
。此外,你真正想要的是带有incrementAndGet
方法的AtomicInteger
。 - obataku