Synchronizing Threads
- In Java, every object has a lock.
- To obtain the lock, you must synchronize with the object.
- The simplest way to use synchronization is by declaring one or more methods to be synchronized
- When a synchronized method is invoked, the calling thread attempts to obtain the lock on the object.
- if it cannot obtain the lock, the thread goes to sleep until the lock becomes available
- Once the lock is obtained, no other thread can obtain the lock until it is released. ie, the synchronized method terminates
- When a thread is within a synchronized method, it knows that no other synchronized method can be invoked by any other thread
- Therefore, it is within synchronized methods that critical data is updated
class Parent
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
class Child extends Thread
{
String msg;
First fobj;
Child (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{
fobj.display(msg);
}
}
}
public class Syncro
{
public static void main (String[] args)
{
Parent fnew = new Parent();
Child ss = new Child(fnew, "welcome");
Child ss1= new Child (fnew,"new");
Child ss2 = new Child(fnew, "programmer");
}
}