您的位置:首页 > 其它

AtomicInteger 使用示例

2017-11-06 00:00 211 查看
摘要: 多线程环节下,计数器。

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 多线程