Using synchronized keyword with methods

Threads can be made synchronous. One of the way is using synchronized method

class FirstSync
{
public FirstSync()
{
}
public synchronized void printHelloWorld()
{
try
{
System.out.print("Hello");
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("First sync interrupted."); }
System.out.print(" World. ");
}
}
class SecondSync
{
public SecondSync()
{
}
public synchronized void printMe()
{
try
{
System.out.print("I am a ");
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Second sync interrupted.");
}
System.out.println("sync method");
}
}
class SyncMethDemo
{
public static void main(String args[])
{
// Get current thread's object
Thread mainThread=Thread.currentThread();
// Set a name to main thread
mainThread.setName("Main Thread");
new Thread(new Runnable(){
public void run()
{
// Create thread objects
FirstSync f=new FirstSync();
f.printHelloWorld();
SecondSync s=new SecondSync();
s.printMe();
}
}).start();
}
}
------------------------------------------
Output :
------------------------------------------
Hello World. I am a sync method


Posted by at on

Tags: Multi Threading, Synchronization,