DS Experiement no 3

Aim- Write a program to implement multithreading synchronization.


import java.io.*;
class First
{
 public void display(String msg)
 {
  System.out.print ("["+msg);
  try
  {
   Thread.sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println ("]");
 }
}

class Second extends Thread
{
 String msg;  
 First fobj;
 Second (First fp,String str)
 {
  fobj = fp;
  msg = str;
  start();
 }
 public void run()
 {
  synchronized(fobj)       //Synchronized block
  {
   fobj.display(msg);
  }
 }
}

public class Syncro
{
 public static void main (String[] args) 
 {
  First fnew = new First();
  Second ss = new Second(fnew, "welcome");
  Second ss1= new Second (fnew,"new");
  Second ss2 = new Second(fnew, "programmer");
 }
}


Output

D:\Java\jdk1.8.0_111>
D:\Java\jdk1.8.0_111>
D:\Java\jdk1.8.0_111> cd bin

D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin> javac Syncro.java

D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>
D:\Java\jdk1.8.0_111\bin>java Syncro
[welcome]
[programmer]
[new]


DS Experiement no 3 DS Experiement no 3 Reviewed by akshay salve on 5:33 PM Rating: 5

No comments:

Powered by Blogger.