Skip to content

Instantly share code, notes, and snippets.

@eaddingtonwhite
Created September 26, 2014 18:15
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 eaddingtonwhite/a42e7149b3851dae1ddd to your computer and use it in GitHub Desktop.
Save eaddingtonwhite/a42e7149b3851dae1ddd to your computer and use it in GitHub Desktop.
Syncronized method in Java
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