Tuesday, January 5, 2016

SYNCHRONIZATION IN THREAD (java)

SYNCHRONIZATION IN JAVA THREAD

Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement:

synchronized(objectidentifier) 
{
// Access shared variables and other shared resources
}

SAMPLE CODE:

public class Sync
{
static Runnable br,br1;
public static void main(String[] args)
{
br=()->{
data();
};
br1=()->{
data();
};
Thread t1=new Thread(br);
t1.start();
Thread t2=new Thread(br1);
t2.start();

}
public synchronized static void data()
{
for(int i=0;i<10;i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Sync.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(i);
}
}

}

No comments:

Post a Comment