Skip to content

Instantly share code, notes, and snippets.

@finnkvan
Created October 24, 2018 20:18
Show Gist options
  • Save finnkvan/7dac7c92b72824533c140bd3ce252237 to your computer and use it in GitHub Desktop.
Save finnkvan/7dac7c92b72824533c140bd3ce252237 to your computer and use it in GitHub Desktop.
Using Volatile
package com.pivincii;
public class Counter {
private volatile int count = 0;
public void increment() {
count ++;
}
public void decrement() {
count --;
}
public int getCount() {
return count;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i ++) {
Counter counter = new Counter();
new Thread(counter::increment).start();
new Thread(counter::decrement).start();
try {
Thread.sleep(10);
} 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