Created
February 9, 2017 22:35
-
-
Save mushketyk/ce91ca5da7a7c5b39a17d2633ba32317 to your computer and use it in GitHub Desktop.
Java synchronization example
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
class IncrementingRunnable implements Runnable { | |
private final MutableInteger mutableInteger; | |
public IncrementingRunnable(MutableInteger mutableInteger) { | |
this.mutableInteger = mutableInteger; | |
} | |
@Override | |
public void run() { | |
for (int i = 0; i < 10_000; i++) { | |
mutableInteger.increment(); | |
} | |
} | |
} | |
public class Main { | |
public static void main (String[] args) { | |
List<Thread> threads = new ArrayList<>(); | |
// Variable to increment from multiple threads | |
MutableInteger integer = new MutableInteger(); | |
// Run 10 threads to increment the same variable | |
for (int i = 0; i < 10; i++) { | |
Thread thread = new Thread(new IncrementingRunnable(integer)); | |
thread.start(); | |
threads.add(thread); | |
} | |
// Wait until all threads are finished | |
for (Thread thread : threads) { | |
thread.join(); | |
} | |
System.out.println("Result value: " + integer.getValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment