Last active
November 27, 2015 12:52
-
-
Save rishi93/4c236f13ffb2f5412235 to your computer and use it in GitHub Desktop.
Synchronized block 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 only thread has access to it at a time */ | |
import java.io.*; | |
class Routine | |
{ | |
private String msg; | |
Routine(String msg) | |
{ | |
this.msg = msg; | |
} | |
public void display() | |
{ | |
System.out.print("[ "); | |
try | |
{ | |
Thread.sleep(1000); | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
System.out.print(msg); | |
try | |
{ | |
Thread.sleep(1000); | |
} | |
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() | |
{ | |
synchronized(ob)/* If this is not synchronized, output is very random */ | |
{ | |
System.out.println("Thread started"); | |
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)); | |
Thread t3 = new Thread(new MyThread(obj)); | |
t1.start(); | |
t2.start(); | |
t3.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment