|
@@ -0,0 +1,32 @@
|
|
|
|
+import java.util.concurrent.*;
|
|
|
|
+import java.util.concurrent.atomic.*;
|
|
|
|
+
|
|
|
|
+public class TestAtomic {
|
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
|
+ int threads = 1000;
|
|
|
|
+ ExecutorService executor = Executors.newCachedThreadPool();
|
|
|
|
+ CountDownLatch cd = new CountDownLatch(threads);
|
|
|
|
+ Counter counter = new Counter();
|
|
|
|
+ for (int i = 0; i < threads; i++) {
|
|
|
|
+ executor.execute(() -> {
|
|
|
|
+ counter.add();
|
|
|
|
+ cd.countDown();
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+ cd.await();
|
|
|
|
+ executor.shutdown();
|
|
|
|
+ System.out.println(counter.get());
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+class Counter {
|
|
|
|
+ private AtomicInteger count = new AtomicInteger(0);
|
|
|
|
+
|
|
|
|
+ void add() {
|
|
|
|
+ count.incrementAndGet();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ int get() {
|
|
|
|
+ return count.get();
|
|
|
|
+ }
|
|
|
|
+}
|