Created
September 26, 2014 18:15
-
-
Save eaddingtonwhite/a42e7149b3851dae1ddd to your computer and use it in GitHub Desktop.
Syncronized method in Java
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
public static synchronized void addValue(int myIndex) { | |
boolean imDone = false; | |
System.out.println("Thread " + myIndex + " is trying to add its value"); | |
do { | |
if (myIndex != numberOfThreadsDone) { | |
try { | |
System.out.println(myIndex + " is about to wait"); | |
ParallelSerial.class.wait(); // <-- ** Important need to call className.class.wait() in syncronized method** | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} else { | |
sum += arrayToSum[myIndex]; | |
numberOfThreadsDone++; | |
imDone = true; | |
ParallelSerial.class.notifyAll(); // <-- ** Important need to call className.class.notifyAll() in syncronized method ** | |
} | |
} while (!imDone); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment