Tread Synchronizing
Tread Synchronizing
Tread Synchronizing
Synchronization. At times when more than one thread try to access a shared resource, we need to
ensure that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. The synchronization keyword in java creates a block of code
referred to as critical section.
class Bucket
{
synchronized public void holdBucket(String Thname)
{
System.out.println("Bucket is holded by "+Thname);
for (int i = 0; i < 10; i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
ThrdName=nm;
bucket=b;
}
public void run()
{
System.out.println(ThrdName+"Holds bucket");
bucket.holdBucket(ThrdName);
System.out.println(ThrdName+"Release bucket");
}
public static void main(String args[])
{
Bucket bucket= new Bucket();
Thread t1, t2,t3;
impBucket b1,b2,b3;
b1= new impBucket("Thread1",bucket);
b2= new impBucket("Thread2",bucket);
b3= new impBucket("Thread3",bucket);
t1= new Thread(b1);
t2= new Thread(b2);
t3= new Thread(b3);
t1.start();
t2.start();
t3.start();
}
}
Synchronized Keyword
To synchronize above program, we must synchronize access to the shared display() method, making
it available to only one thread at a time. This is done by using keyword synchronized with display()
method.
synchronized void display (String msg)
The Object class in Java has three final methods that allow threads to communicate about the
locked status of a resource. These are :
1. wait() : It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify(). The wait() method releases the lock prior
to waiting and reacquires the lock prior to returning from the wait() method. The
wait() method is actually tightly integrated with the synchronization lock, using a feature
not available directly from the synchronization mechanism. In other words, it is not possible
for us to implement the wait() method purely in Java: it is a native method.
lockObject.notify();
lockObject.notifyAll();
}