TestThreadUnsafe.java 722 B

12345678910111213141516171819202122232425262728293031
  1. import java.util.concurrent.*;
  2. public class TestThreadUnsafe {
  3. public static void main(String[] args) throws Exception {
  4. int threads = 1000;
  5. ExecutorService executor = Executors.newCachedThreadPool();
  6. CountDownLatch cd = new CountDownLatch(threads);
  7. Counter counter = new Counter();
  8. for (int i = 0; i < threads; i++) {
  9. executor.execute(() -> {
  10. counter.add();
  11. cd.countDown();
  12. });
  13. }
  14. cd.await();
  15. executor.shutdown();
  16. System.out.println(counter.get());
  17. }
  18. }
  19. class Counter {
  20. private int count = 0;
  21. void add() {
  22. count++;
  23. }
  24. int get() {
  25. return count;
  26. }
  27. }