Created
October 24, 2018 20:16
-
-
Save finnkvan/4856ca77c7ac024740ada757da71b14d to your computer and use it in GitHub Desktop.
AtomicCounter
This file contains hidden or 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
| package com.pivincii; | |
| import java.util.concurrent.atomic.AtomicInteger; | |
| public class Counter { | |
| private AtomicInteger count = new AtomicInteger(0); | |
| public void increment() { | |
| count.getAndIncrement(); | |
| } | |
| public void decrement() { | |
| count.getAndDecrement(); | |
| } | |
| public int getCount() { | |
| return count.get(); | |
| } | |
| public static void main(String[] args) { | |
| for (int i = 0; i < 3; i ++) { | |
| Counter counter = new Counter(); | |
| new Thread(counter::increment).start(); | |
| new Thread(counter::decrement).start(); | |
| try { | |
| Thread.sleep(100); | |
| } catch (InterruptedException e) { | |
| e.printStackTrace(); | |
| } | |
| System.out.println(counter.getCount()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment