Synchronization Java U-4
Synchronization Java U-4
UNIT-IV
Threads, creating threads, extending the threads class,
stopping and blocking a thread, life cycle of a thread,
using thread methods, thread exceptions, thread priority,
synchronization, implementing the unable interface.
Synchronization:
We know that threads uses their own data and methods
provided inside their run() method.consider a
case when they try to use data and methods outside
themselves.In such situation they may compete
for the same resurce and may lead to serious problems.
for an instance suppose there are two threads, one they
may reading the data from the resurce and
the second thread may be writing data at the same time.In
such situation, result will be unexpexted.Java enables us
to overcome this situation using a technique called
Synchronization.
Synchronization
The keyword Synchronized helps to solve problem by
keeping watch on such locations. to avoid issues
the methods that will read information and the method
that will write information may be declared as
Synchronized.For example:
Synchronizedvoid update()
{
----------
----------
}
JAVA
UNIT-IV
Synchronizedvoid read()
{
----------
----------
}
When we declare a method as synchronized, java creates a
"monitor" and hands it over to the
thread that calls the method first time.As long as the tread
holds the monitor, no other thread
can enter the synchronized section of code.
It is also possible to make a block of code as synchronized:
synchronized(lock-object)
{
}
Example:
class printing
{
void print(char ch)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(ch);
}
System.out.println();
}
}
}
JAVA
UNIT-IV
class A extends Thread
{
printing p;
A(printing p)
{
this.p=p;
}
public void run(){
p.print('*');
}
}
class B extends Thread
{
printing p;
B(printing p)
{
this.p=p;
}
public void run(){
p.print('#');
}}
class synchronization
{
public static void main(String args[])
{
printing aa=new printing();
A threadA=new A(aa);
B threadB=new B(aa);
threadA.start();
threadB.start();
}}