Java Thread Synchronization
Consider a multi-threaded environment in which a thread access write and read of a same resource thread, java gives wrong output.
Consider a scenario in which java access a resource in which one thread does the read operation and write thread does the write operation then file will be corrupted, locking the access is necessary to overcome this.
Try out this example to understand better
import java.lang.*;
class MyThread extends Thread
{
static String message[] = {”I”, “LOVE”, “JAVA”, “VERY”, “MUCH”};
public MyThread(String id)
{
super(id);
}
public void run()
{
Sync.displayList(getName(),message);
}
void waiting()
{
try
{
sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(”Interrupted”);
}
}
}
class Sync
{
public static void displayList(String name, String list[])
{
for(int i = 0; i < list.length ; i++)
{
MyThread thread = (MyThread)Thread.currentThread();
thread.waiting();0
System.out.println(name + list[i]);
}
}
}
class ThreadSync
{
public static void main(String args[])
{
MyThread thread1 = new MyThread(”Thread 1:”);
MyThread thread2 = new MyThread(”Thread 2:”);
thread1.start(); //starts first thread
thread2.start(); //starts second thread
}
}