Last active
October 2, 2019 07:26
-
-
Save calvinnor/b199a8ab9c8f82cb978ecede92c677d0 to your computer and use it in GitHub Desktop.
A Java Execution manipulating a shared variable, with Synchronisation
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
public class WithSync { | |
private static final int NUM_EXECUTIONS = 100000000; | |
// This Object ensures synchronization | |
private static final Object mutexLock = new Object(); | |
private static void someLongOperation() { /* NO-OP */ } | |
public static void main(String[] args) { | |
final long[] numElements = {0}; | |
Thread incrementThread = new Thread() { | |
@Override | |
public void run() { | |
for (long count = 0; count < NUM_EXECUTIONS; count++) { | |
someLongOperation(); | |
synchronized(mutexLock) { | |
numElements[0] += 1; | |
} | |
} | |
} | |
}; | |
Thread decrementThread = new Thread() { | |
@Override | |
public void run() { | |
for (long count = 0; count < NUM_EXECUTIONS; count++) { | |
someLongOperation(); | |
synchronized(mutexLock) { | |
numElements[0] -= 1; | |
} | |
} | |
} | |
}; | |
// Start the threads | |
incrementThread.start(); decrementThread.start(); | |
// Wait for jobs to finish | |
try { incrementThread.join(); decrementThread.join(); } | |
catch (InterruptedException e) { /* NO-OP */ } | |
// Print the result | |
System.out.println("Result is: " + numElements[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment