AtomicInteger (保证多线程情况下的原子操作)
public class AtomicIntegerDemo {
public static AtomicInteger count = new AtomicInteger(0);
public static void inc(){
try{
Thread.sleep(1); //延迟1毫秒
}catch (InterruptedException e){ //catch住中断异常,防止程序中断
e.printStackTrace();
}
count.getAndIncrement();//count值自加1
}
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(100);
for(int i=0;i<100;i++){
new Thread(new Runnable() {
@Override
public void run() {
AtomicIntegerDemo.inc();
latch.countDown();
}
}).start();
}
latch.await();
System.out.println("运行结果:"+AtomicIntegerDemo.count);
}
}
运行结果
运行结果:100
Process finished with exit code 0
网友评论