Skip to content

Instantly share code, notes, and snippets.

@lihongjie0209
Created December 5, 2018 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lihongjie0209/b97dd98b24a454d56c3531a93dccc62d to your computer and use it in GitHub Desktop.
Save lihongjie0209/b97dd98b24a454d56c3531a93dccc62d to your computer and use it in GitHub Desktop.
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