Synchronization

From the concept of multithreading, joining threads is termed synchronization. Usually, the main thread needs to wait until the processing threads have finished with their execution. Also, multiple threads should be safeguarded not to update a shared resource called mutual exclusion, which is achieved with the usage of the keyword called synchronized. Statements and methods referred to with the synchronized keyword can be accessed and updated by only one process at a time. One thread has to wait for the other to complete the processing of the synchronized block and communicate with the wait() and notifyall() methods to let other threads know they need to wait and allow this other thread to be executed first.

The following is a sample program for synchronization, using the synchronized keyword:

package threads;

public class SynchronizeThreads {

int threadNumber;
ThreadCounter threadCounter;
public SynchronizeThreads(int threadNumber,ThreadCounter threadCounter) {
this.threadNumber = threadNumber;
this.threadCounter=threadCounter;
}
public void ThreadBarrier() {
synchronized (threadCounter) {
threadCounter.sharedAccessCont++;
try {
if(threadCounter.sharedAccessCont != threadNumber) {
threadCounter.wait();
} else {
threadCounter.sharedAccessCont = 0;
threadCounter.notifyAll();
}
}
catch (InterruptedException e) {
System.out.println("From Synchronized block execution");
}
}
}
}
class ThreadCounter {
int sharedAccessCont;
public ThreadCounter(int sharedAccessCont) {
this.sharedAccessCont=sharedAccessCont;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset