Synchronized in Java : To make sure that only one Thread can access to the resource at a given point of time, we use Synchronized !!

In many time, Multi-threaded programs provide a situation where multiple threads try to access the same resources and finally produce erroneous result !

To solve this problem , Java provides a way of creating threads and synchronizing their task by using synchronized blocks !

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

Following is an example of multi threading with synchronized :

// A Java program to demonstrate working of 
// synchronized. 
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); 
		} 
	} 
} 

// Driver class 
class SyncDemo 
{ 
	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:

Sending     Hi 

 Hi Sent
Sending     Bye 

 Bye Sent

We can use Synchronized with method also instead of a block of code:

public synchronized void send(String msg) 
 {
     ......
           }

Tagged:

Commentaires

  1. Pingback: Thread Class vs Runnable Interface » JavaTuto

Laisser un commentaire