Created
December 5, 2018 00:22
-
-
Save lihongjie0209/b97dd98b24a454d56c3531a93dccc62d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Counter { | |
private static int count = 0; | |
public static synchronized int getCount() { | |
return count; | |
} | |
public synchronized void setCount(int count) { | |
this.count = count; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
ExecutorService threadPool = Executors.newCachedThreadPool(); | |
for (int i = 0; i < 10; i++) { | |
threadPool.submit(() -> { | |
Counter counter = new Counter(); | |
counter.setCount(Counter.getCount() + 1); | |
}); | |
} | |
threadPool.shutdown(); | |
threadPool.awaitTermination(1, TimeUnit.SECONDS); | |
System.out.println(Counter.getCount()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment