AtomicInteger 使用示例
2017-11-06 00:00
211 查看
摘要: 多线程环节下,计数器。
输出结果:
End=== Thread:11
End=== Thread:15
End=== Thread:10
End=== Thread:9
End=== Thread:12
End=== Thread:14
End=== Thread:16
End=== Thread:18
End=== Thread:13
End=== Thread:17
总共耗时:1005 data=10
public class VolatileTest { static AtomicInteger data = new AtomicInteger(); public static void main(String[] args) { int num = 10; long time = System.currentTimeMillis(); ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); final CountDownLatch latch = new CountDownLatch(num); for (int i = 0; i < 10; i++) { cachedThreadPool.execute(new Runnable() { public void run() { try { Thread.sleep(1000); data.getAndIncrement(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(" End=== Thread:"+Thread.currentThread().getId()); latch.countDown(); } }); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("总共耗时:" + (System.currentTimeMillis()-time)+" data="+data.get()); cachedThreadPool.shutdown(); } }
输出结果:
End=== Thread:11
End=== Thread:15
End=== Thread:10
End=== Thread:9
End=== Thread:12
End=== Thread:14
End=== Thread:16
End=== Thread:18
End=== Thread:13
End=== Thread:17
总共耗时:1005 data=10
相关文章推荐
- AtomicInteger的认识与使用
- java中关于AtomicInteger的使用
- 【Java多线程】AtomicInteger使用
- Java中的Atomic包使用指南:AtomicInteger、AtomicBoolean、AtomicIntegerArray、AtomicReference……
- 使用 AtomicInteger 进行计数(java多线程优化)
- 无锁类的使用---AtomicInteger
- JAVA中无锁的线程安全整数AtomicInteger介绍和使用
- Java之voliate, synchronized, AtomicInteger使用
- Java之voliate, synchronized, AtomicInteger使用
- concurrent.atomic包下的类AtomicInteger的使用
- AtomicInteger使用
- AtomicInteger的使用
- AtomicInteger 在高并发量应用程序中的使用及volatile说明
- Java 并发机制(synchronize/Lock/volitale/CAS/AtomicInteger)的使用和实现
- Java中AtomicInteger的使用!!!
- 10048--- AtomicInteger的介绍和使用
- JAVA 中无锁的线程安全整数 AtomicInteger介绍和使用
- Java中AtomicInteger的使用!!!
- Java之voliate, synchronized, AtomicInteger使用
- AtomicInteger的介绍和使用