What is Thread Synchronization?
When multiple thread try to access the same resource. Thread Synchronization is a technique which is used to synchronize multiple threads and make sure that only one thread can access the resource at a given point in time.
For Example: if multiple threads A and B try to write within a same file then they may corrupt the data because one of the thread A can override data or while one thread B is opening the same file at the same time another thread A might be closing the same file.
How to Synchronize thread?
Java provides the Synchronized block to synchronize the Threads. Synchronized block in Java used by Synchronized Keyword. A Synchronized block is Synchronized on some objects. Synchronized blocks synchronized on the same object can only one thread executing at a time by the block. All the other thread blocked and waiting for the end of the execution of the thread which is inside the Synchronized block.
Synchronization is implemented by Monitors in Java. Every thread object in Java thread synchronization is associated with a Monitor. Only one thread use the Monitor at a time. Monitor provides a lock when a thread enter in the Synchronized Block. All other threads trying to enter the locked monitor will be suspended until the first thread exits the monitor.
Syntax:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents.
Example of Thread Syncronization in Java
// thread Synchronization in Java with Example.
import java.io.*;
import java.util.*;
// A Class used to send a message
class Sender
{
public void send(String msg)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
// Class for send a message using Threads
class ThreadedSend extends Thread
{
private String msg;
Sender sender;
// Recieves a message object and a string
// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}
public void run()
{
// Only one thread can send a message
// at a time.
synchronized(sender)
{
// synchronizing the snd object
sender.send(msg);
}
}
}
// Main Class
class Sync
{
public static void main(String args[])
{
Sender snd = new Sender();
ThreadedSend S1 =
new ThreadedSend( " Hi " , snd );
ThreadedSend S2 =
new ThreadedSend( " Bye " , snd );
// Start two threads of ThreadedSend type
S1.start();
S2.start();
// wait for threads to end
try
{
S1.join();
S2.join();
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}
Output: