1、Atomic*是什么
java 提供了很多原子类来保证并发下的正确性和提升并发能力
2、Atomic*的用法
Atomic* 类提供的方法基本类似,我就挑出AtomicInteger来说明
public class AtomicTest {
private static final AtomicInteger count = new AtomicInteger();
private static final CountDownLatch start = new CountDownLatch(1);
private static final CountDownLatch end = new CountDownLatch(10);
private static final Object obj = new Object();
public static void main(String[] args) throws InterruptedException {
for (int i =0 ;i < 100 ;i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
start.await();
//task
System.out.println("原子类在并发情况下的输出:"+count.addAndGet(1));
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
end.countDown();
}
}
});
thread.start();
}
start.countDown();
end.await();
}
上面输出结果不是顺序性(但是结果不会出现重复记录,由于存在字符串拼接)
8万+

被折叠的 条评论
为什么被折叠?



