写在前面

来个大佬看看我的解决办法对不对。。。啊啊啊!!!

求评论!!!求解答!!!

(1)解决办法是否正确?

(2)如果错误,具体原因是什么?CountDownLatch使用的是否有问题?


线程不安全的场景

public class CASTest1 {

int i = 0;

public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);

CASTest1 casTest = new CASTest1();

new Thread(() -> {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
casTest.i++;
}
}).start();

new Thread(() -> {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
casTest.i++;
}
}).start();

//Thread.sleep(3000);

System.out.println(casTest.i);
}
}


解决办法

public class CASTest3 {
AtomicInteger i = new AtomicInteger();
//int i = 0;

public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);

CASTest3 casTest = new CASTest3();

new Thread(() -> {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//casTest.i++;
casTest.i.getAndIncrement();
}
countDownLatch.countDown();
}).start();

new Thread(() -> {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//casTest.i++;
casTest.i.getAndIncrement();
}
countDownLatch.countDown();
}).start();

//Thread.sleep(900);
countDownLatch.await();
System.out.println(casTest.i.get());
}
}