Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active November 27, 2015 12:48
Show Gist options
  • Save rishi93/31b70bdc1fa1784ee463 to your computer and use it in GitHub Desktop.
Save rishi93/31b70bdc1fa1784ee463 to your computer and use it in GitHub Desktop.
Synchronized function in Multithreading
/*Synchronized means the code is available to only thread at a time */
import java.io.*;
class Routine
{
private String msg;
Routine(String msg)
{
this.msg = msg;
}
public synchronized void display() /* If this is not synchronized, output is very random */
{
System.out.print("[ ");
try
{
Thread.sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.print(msg);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(" ]");
}
}
class MyThread implements Runnable
{
private Routine ob;
MyThread(Routine ob)
{
this.ob = ob;
}
@Override
public void run()
{
ob.display();
}
}
public class test2
{
public static void main(String[] args)
{
Routine obj = new Routine("Hi");
Thread t1 = new Thread(new MyThread(obj));
Thread t2 = new Thread(new MyThread(obj));
t1.start();
t2.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment