Skip to content

Instantly share code, notes, and snippets.

@mushketyk
Created February 9, 2017 22:35
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 mushketyk/ce91ca5da7a7c5b39a17d2633ba32317 to your computer and use it in GitHub Desktop.
Save mushketyk/ce91ca5da7a7c5b39a17d2633ba32317 to your computer and use it in GitHub Desktop.
Java synchronization example
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