Generally threads use their own data and methods provided inside their run() methods. But if we wish to use data and methods outside the thread’s run() method, they may compete for the same resources and may lead to serious problems. For example, one thread may try to read a record from a file while another is still writing to the same file. Depending on the situation, we may get strange results. Java enables us to overcome this problem using a technique known as synchronization.
In case of Java, the keyword synchronized helps to solve such problems by keeping a watch on such locations. For example, the method that that will update a file may be declared as synchronized as shown below:
synchronized void update( )
{
………….. // code here is synchronized
}
When we declare a method synchronized, Java creates a "monitor" and hands it over to the thread that calls the method first time. As long as the thread runs, no other thread can enter the synchronized section of code i.e. other threads cannot interrupt this thread with that object until its complete execution. It is like locking a function.
It is also possible to mark a block of code as synchronized as shown below:
synchronized (lock-object)
{
.......... // code here is synchronized
}
Whenever a thread has completed its work of using synchronized method (or block of code), it will hand over the monitor to the next thread that is ready to use the same resource.
class Alpha
{
public synchronized void show(String s)
{
System.out.print("["+s);
try { Thread.sleep(1000); } catch(Exception e) { }
System.out.print(“]“);
}
}
class MyThread implements Runnable
{
Thread t;
Alpha a1;
String s;
MyThread(Alpha a,String ss)
{
t=new Thread(this);
s=ss;
a1=a;
}
public void run()
{
a1.show(s);
}
}
class Test
{
public static void main(String as[])
{
Alpha a1 = new Alpha();
MyThread t1=new MyThread(a1,"One");
MyThread t2=new MyThread(a1,"Two");
t1.t.start();
t2.t.start();
}
}
The above program generates the following output:
[One][Two]
Note: if the method is not synchronized one, the output will be [One[Two]] i.e. leading to improper (partial) execution of the method before another thread catches up.
0 comments:
Post a Comment