返回信息流public class ThreadsDemo {
public static int n = 0;
private static final int NTHREADS = 10;
public static void main(String[] argv) throws InterruptedException {
final AtomicInteger count = new AtomicInteger();
final CountDownLatch cdl = new CountDownLatch(NTHREADS);
for (int i = 0; i < NTHREADS; i++) {
final int i2 = i;
new Thread(new Runnable() {
public void run() {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(i2 + " before, n is: " + n);
n += 1;
System.out.println(i2 + " after , n is: " + n);
count.incrementAndGet();
cdl.countDown();
}
}).start();
}
cdl.await();
System.out.println("count is: " + count.get());
System.out.println("fxxk, n is: " + n);
}
}
1 before, n is: 0
4 before, n is: 0
3 before, n is: 0
2 before, n is: 0
2 after , n is: 4
0 before, n is: 0
6 before, n is: 4
6 after , n is: 6
3 after , n is: 3
4 after , n is: 2
8 before, n is: 6
8 after , n is: 7
5 before, n is: 2
1 after , n is: 1
5 after , n is: 8
9 before, n is: 7
9 after , n is: 9
7 before, n is: 5
7 after , n is: 10
0 after , n is: 5
count is: 10
fxxk, n is: 10
Process finished with exit code 0
加上sleep之后n就不正确了。。。求解释Java到底做了啥优化吗
这是一条镜像帖。来源:北邮人论坛 / java / #56065同步于 2017/4/27
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
为什么没有race condition?
westorb
2017/4/27镜像同步10 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
synchronized。引入了锁。多了lock#和mem barrier,然而并不能解决这个问题呢,少年,这里还需要的是原子加一,也就是需要在n+=1周围进行加锁或者利用cas原子指令,println
里的锁没用吧。。
【 在 westorb (打完球吃西瓜) 的大作中提到: 】
: [code=java]
: public class ThreadsDemo {
: public static int n = 0;
: ...................
通过『我邮2.0』发布
public class ThreadsDemo {
public static int n = 0;
private static final int NTHREADS = 300;
public static void main(String[] argv) throws InterruptedException {
final AtomicInteger count = new AtomicInteger();
final CountDownLatch cdl = new CountDownLatch(NTHREADS);
for (int i = 0; i < NTHREADS; i++) {
new Thread(new Runnable() {
public void run() {
n += 1;
count.incrementAndGet();
cdl.countDown();
}
}).start();
}
cdl.await();
System.out.println("count is: " + count.get());
System.out.println("fxxk, n is: " + n);
}
}
count is: 300
fxxk, n is: 300
Process finished with exit code 0
【 在 lovemaker 的大作中提到: 】
: 少年,你去看看system.out.println的源码;然后去掉试试看吧,呵呵
加个sleep
【 在 westorb 的大作中提到: 】
: [code=java]
: public class ThreadsDemo {
: public static int n = 0;
: ...................
谁说没有race condition?明明有。
多个线程同时访问共享非volatile变量n,却没有任何形式的同步,这就是data race。
这里只用volitale修饰也还是不够的~
【 在 nuanyangyang (暖羊羊) 的大作中提到: 】
: 谁说没有race condition?明明有。
: 多个线程同时访问共享非volatile变量n,却没有任何形式的同步,这就是data race。
通过『我邮2.0』发布