Created
October 24, 2018 20:18
-
-
Save finnkvan/7dac7c92b72824533c140bd3ce252237 to your computer and use it in GitHub Desktop.
Using Volatile
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; | |
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