以下代码没有保证并发编程下的原子性、有序性、可见性
public class Study {
public static void main(String[] args) {
Person66 person66 = new Person66();
CountDownLatch countDownLatch = new CountDownLatch(10);
try{
for (int j=1;j<=10;j++) {
new Thread(()->{
for (int i=1;i<=1000;i++){
person66.count();
}
countDownLatch.countDown();
},String.valueOf(j)).start();
}}catch (Exception e){
e.printStackTrace();
}finally {
//上面线程未完成前让主线程等待
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(person66.number);
}
}
class Person66{
int number=0;
public void count(){
number++;
}
}
经过多次运行 最终的值可能为9864(随机),可见数据不如预期(10000)
这个结果得多跑几次
解决方法:
1.volatile+synchronized
public class Study {
public static void main(String[] args) {
Person66 person66 = new Person66();
CountDownLatch countDownLatch = new CountDownLatch(10);
try{
for (int j=1;j<=10;j++) {
new Thread(()->{
for (int i=1;i<=1000;i++){
person66.count();
}
countDownLatch.countDown();
},String.valueOf(j)).start();
}}catch (Exception e){
e.printStackTrace();
}finally {
//上面线程未完成前让主线程等待
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(person66.number);
}
}
class Person66{
volatile int number=0;
public synchronized void count(){
number++;
}
}
2.使用原子类(volatile+CAS)
public class Study {
public static void main(String[] args) {
Person66 person66 = new Person66();
CountDownLatch countDownLatch = new CountDownLatch(10);
try{
for (int j=1;j<=10;j++) {
new Thread(()->{
for (int i=1;i<=1000;i++){
person66.count();
}
countDownLatch.countDown();
},String.valueOf(j)).start();
}}catch (Exception e){
e.printStackTrace();
}finally {
//上面线程未完成前让主线程等待
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(person66.number);
}
}
class Person66{
AtomicInteger number = new AtomicInteger(0);
public void count(){
number.addAndGet(1);
}
}