Skip to content

Instantly share code, notes, and snippets.

@magicly
Created December 15, 2014 05:10
Show Gist options
  • Save magicly/56e666e1c56819f9ce57 to your computer and use it in GitHub Desktop.
Save magicly/56e666e1c56819f9ce57 to your computer and use it in GitHub Desktop.
why not n == 10
package concurrent;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by magicalli on 2014/12/13.
*/
public class IndexPlusPlusTest {
private volatile static int n = 0;
private static int m = 0;
private volatile static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
// synchronized (IndexPlusPlusTest.class) {
// atomicInteger.addAndGet(1);
synchronized (IndexPlusPlusTest.class) {//因为已经有thread开始了,所以同步没用???
n++;
}
}
}).start();
}
// ExecutorService pool = Executors.newCachedThreadPool();
// for (int i = 0; i < 10; i++) {
// pool.submit(new Runnable() {
// @Override
// public void run() {
// m++;
// }
// });
// }
System.out.println("n:" + n);
System.out.println("m:" + m);
System.out.println("atomicInteger:" + atomicInteger);
}
}
@magicly
Copy link
Author

magicly commented Dec 15, 2014

额,犯傻了,因为Thread还没有执行完成, System.out.println("n:" + n);就先执行了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment