Categories
Uncategorized

Synchronization of Thread

Q) WAP to implements Thread Synchronization in Java.

import java.util.Scanner;

class Table{   
     void printTable(int n){ 
     synchronized(this){//synchronized block 
     for(int i=1;i<=10;i++){
             System.out.println(n+”*”+i+”=”+n*i); 
     try{ 
             Thread.sleep(400); 
         }catch(Exception e){System.out.println(e);} 
      } 
    } 
         }
}   

public class sync{ 
     public static void main(String args[])
     { 
         final Table obj = new Table();//only one object
         System.out.println(“Enter two number to see the multiplication table of:”);  
         Thread t1=new Thread(){ 
             public void run(){
             Scanner s=new Scanner(System.in);
             int a;
             a=s.nextInt();
             obj.printTable(a); 
                 } 
             }; 
         Thread t2=new Thread(){ 
         public void run(){ 
         Scanner s=new Scanner(System.in);
         int a;
         a=s.nextInt();
         obj.printTable(a); 
                 } 
             };   
         t1.start(); 
         t2.start(); 
     } 

Reference:javatpoint.com

One reply on “Synchronization of Thread”

Comments are closed.