Last active
November 27, 2015 12:48
-
-
Save rishi93/31b70bdc1fa1784ee463 to your computer and use it in GitHub Desktop.
Synchronized function in Multithreading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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