Skip to content

Instantly share code, notes, and snippets.

@mushketyk mushketyk/Main.java
Created Feb 9, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.