一 多线程原子性
1.1 基本数据类型原子
atomicInteger, atomicLong,atomicBoolean
代码
package com.ljf.thread.atomic;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
class MyNumber
{
AtomicInteger atomicInteger = new AtomicInteger();
public void addPlusPlus()
{
atomicInteger.getAndIncrement();
}
}
/**
* @ClassName: AtomicDemo
* @Description: TODO
* @Author: admin
* @Date: 2023/11/06 22:24:14
* @Version: V1.0
**/
public class AtomicDemo {
public static void main(String[] args) throws InterruptedException {
MyNumber myNumber = new MyNumber();
CountDownLatch ct=new CountDownLatch(10);
for(int k=1;k<=10;k++){
new Thread(new Runnable() {
@Override
public void run() {
for(int k=0;k<30;k++){
myNumber.addPlusPlus();
}
ct.countDown();
}
},String.valueOf(k)).start();
}
ct.await();
System.out.println("");
System.out.println(Thread.currentThread().getName()+"\t"+"result: "+myNumber.atomicInteger.get());
}
}
结果: