1、 代码案例: 借助 AtomicInteger 实现线程安全计数器
package multiThread.art;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 使用循环 CAS 实现原子操作
*/
public class CasDemo {
/**
* 创建具有给定初始值的新 AtomicInteger
*/
private AtomicInteger atomicI = new AtomicInteger(0);
/**
* 实例私有的属性变量
*/
private int i = 0;
public static void main(String[] args) {
final CasDemo cas = new CasDemo();
List<Thread> ts = new ArrayList<Thread>();
long start = System.currentTimeMillis();
// 创建 100 个线程,并添加到 ts 的集合中
for( int j = 0 ; j < 100 ; j++){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for( int i = 0 ; i < 1000 ; i++){
// 执行线程安全的计数器 , 每个线程执行 1000 次
cas.safeCount(cas);
// 执行非线程安全计数器
//cas.unSafeCount();
}
}
});
ts.add(t);
}
// 依次启动 ts 集合中的线程
for( Thread t : ts){
t.start();
}
// 等待所有的线程执行完成
for( Thread t : ts){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("运行结束后:cas.i 的值为" + cas.i);
System.out.println("运行结束后:计数器 atomicI 的值为 " + cas.atomicI.get());
System.out.println("运行所消耗的时间:" + (System.currentTimeMillis() - start));
}
/**
* 使用 CAS 实现线程安全计数器
*/
private void safeCount(final CasDemo cas){
// 循环 CAS
for( ; ; ){
/**
* public final int get()
* 获取当前值
*/
int i = atomicI.get();
System.out.println("获取到的值为:"+ i);
/**
* public final boolean compareAndSet(int expect,int update)
* 如果当前值 == 预期值,则以原子的方式将该值设置为给定的更新值
*/
boolean suc = atomicI.compareAndSet(i,++i);
System.out.println("更新的结果为:" + suc);
if( suc ){
cas.i = atomicI.get();
break;
}
}
}
/**
* 非线程安全计数器
*/
private void unSafeCount(){
i++;
}
}