Skip to main content

Assignment No:2

//Assignment No:2


Set A

 a) Program to define a thread for printing text on output screen for ‘n’ number of times. Create 3 threads and run them. Pass the text ‘n’ parameters to the thread constructor. Example: 

i. First thread prints “COVID19” 10 times. 

ii. Second thread prints “LOCKDOWN2020” 20 times 

iii. Third thread prints “VACCINATED2021” 30 times


CODE

šŸ‘‡

  1. import java.util.*;
  2. class Mythread extends Thread
  3. {
  4. String msg;
  5. int n;
  6. Mythread(String m,int a)
  7.  {
  8.   msg=m;
  9.   n=a;
  10.   }
  11.   public void run()
  12.    {
  13.      for(int i=0; i<n; i++)
  14.       System.out.println(msg+ " "+i);
  15.      }
  16.    }
  17. public class disease
  18.  {
  19.    public static void main(String[] args)
  20.    {
  21.   Mythread m1=new Mythread("COVID19",10) ;    
  22.   Mythread m2=new Mythread("LOCKDOWN2020",20) ;    
  23.   Mythread m3=new Mythread("VACCINATED2021",30) ;    
  24.    m1.start();
  25.    m2.start();
  26.    m3.start();
  27.    }
  28.  }

b) Write a program in which thread sleep for 6 sec in the loop in reverse order from 100 to 1 and change the name of thread. 

CODE
šŸ‘‡
  1. import java.io.*;
  2. class reverse_thread
  3. {
  4.  public static void main(String[] args)
  5.  {
  6.  Thread t=Thread.currentThread();
  7.  System.out.println("Current Thread is: "+t);
  8.  t.setName("My Thread");
  9.  System.out.println("After changing the name thread is:" +t);
  10.  try
  11.  {
  12.   for(int n=10; n>0;n--)
  13.   {
  14.     System.out.println(n);
  15.     Thread.sleep(6000);
  16.     }
  17.   }
  18.  catch(Exception e)
  19.  {
  20.   System.out.println(e);
  21.   }
  22.  }  
  23. }

c) Write a program to solve producer consumer problem in which a producer produces a value and consumer consume the value before producer generate the next value. (Hint: use thread synchronization) 

CODE
šŸ‘‡
  1. import java.io.*;
  2. import java.lang.*;
  3. class Shared
  4. {
  5.  int a;
  6.  boolean valueChanged=false;
  7.  synchronized int get_data()
  8.  {
  9.    if(!valueChanged)
  10.    try
  11.     {
  12.      wait();
  13.      }
  14.   catch(InterruptedException e)
  15.    {
  16.     System.out.println("Interrupted");
  17.    }
  18.        System.out.println("Read:" +a);
  19.        valueChanged=false;
  20.        notify();
  21.        return a;
  22.    }
  23.  synchronized void put_data(int n)
  24.  {
  25.    if(valueChanged)
  26.  try
  27.    {
  28. wait();
  29.    }
  30. catch(InterruptedException e)
  31. {
  32.    System.out.println("Interrupted");
  33.   }
  34.  this.a=n;
  35.  valueChanged=true;
  36.     System.out.println("Written: "+a);
  37.     notify();
  38.   }
  39. }

  40. class Producer implements Runnable
  41. {
  42.  Shared ob;
  43.  Producer(Shared ob)  
  44.  {
  45.    this.ob=ob;
  46.    new Thread(this,"Producer").start();
  47.    }
  48. public void run()
  49. {
  50.  int j=0;
  51.   while(true)
  52.    {
  53.     ob.put_data(j++);
  54.    }
  55.  }
  56. }

  57. class Consumer implements Runnable
  58. {
  59.  Shared ob;
  60.  Consumer(Shared ob)
  61.  {
  62.   this.ob=ob;
  63.   new Thread(this,"Consumer").start();
  64.    }
  65. public void run()
  66. {
  67.   while(true)
  68.    {
  69.     ob.get_data();
  70.    }
  71.  }
  72. }       
  73.     
  74. class  sync
  75. {
  76.  public static void main(String args[])throws IOException 
  77.  {
  78.    Shared ob=new Shared();
  79.    new Producer(ob);
  80.    new Consumer(ob);
  81.    System.out.println("Press Ctrl+c to stop");
  82.    }
  83. }
Set B
 a) Write a program to calculate the sum and average of an array of 1000 integers (generated randomly) using 10 threads. Each thread calculates the sum of 100 integers. Use these values to calculate average. [Use join method ].

CODE
šŸ‘‡
  1. import java.util.*;
  2. class thread implements Runnable
  3.  {
  4.    Thread t;
  5.    int i,no,sum;
  6.    int a[]=new int[1000];
  7.    thread(String s,int n)
  8.    {
  9.      Random rs=new Random();
  10.      t=new Thread(this,s);
  11.      n=no;
  12.      int j=0;
  13.      for(i=0; i<1000; i++)
  14.       {
  15.          a[j]=rs.nextInt()%100;
  16.          j++;
  17.        }
  18.      t.start();
  19.     }
  20. public void run()
  21. {
  22.  for(i=0; i<1000; i++)
  23.   {
  24.      sum=sum+a[no];
  25.      no++;
  26.     }
  27.  System.out.println("Sum =" +sum);
  28.  System.out.println("Avg =" +sum/100);
  29.   }
  30.  }    
  31. public class calc
  32. {
  33.   public static void main(String[] args)throws Exception
  34.   {
  35.  thread t1=new thread("a",0);
  36.    t1.t.join();
  37.   thread t2=new thread("b",100);
  38.    t2.t.join();
  39.   thread t3=new thread("c",200);
  40.    t3.t.join();
  41.   thread t4=new thread("d",300);
  42.    t4.t.join();
  43.   thread t5=new thread("e",400);
  44.    t5.t.join();
  45.   thread t6=new thread("f",500);
  46.    t6.t.join();
  47.   thread t7=new thread("g",600);
  48.    t7.t.join();
  49.   thread t8=new thread("i",700);
  50.    t8.t.join();
  51.   thread t9=new thread("j",800);
  52.    t9.t.join();
  53.   thread t10=new thread("k",900);
  54.     t10.t.join();        
  55.    }
  56. }

 b) Write a program for a simple search engine. Accept a string to be searched. Search for the string in all text files in the current folder. Use a separate thread for each file. The result should display the filename, line number where the string is found. 

CODE
šŸ‘‡
  1. import java.io.*;
  2. import java.util.*;
  3. public class search_engine extends Thread
  4. {
  5.   File f1;
  6.   String fname ,line;
  7.   static String str;
  8.   LineNumberReader r=null;
  9.   
  10.   search_engine(String fname)
  11.   {
  12.    this.fname=fname;
  13.    f1=new File(fname);
  14.   }
  15.   
  16. public void run()
  17. {
  18.    try
  19.      {
  20.         FileReader fr=new FileReader(f1);
  21.         r=new LineNumberReader(fr);
  22.         while((line=r.readLine())!=null)
  23.           { 
  24.              if(line.indexOf(str)!=-1)
  25.               {
  26.                  System.out.println("String found in "+fname+ " at "+r.getLineNumber()+ " line");
  27.                  stop();
  28.                 }
  29.          }
  30.    }
  31. catch(Exception e)
  32.  {
  33.   System.out.println(e);
  34.   }  
  35. }
  36. public static void main(String[] args)throws IOException
  37.  {
  38.    Thread t[]=new Thread[20];
  39.    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  40.    System.out.println("Enter String to be Search :");
  41.    str=br.readLine();
  42.    FilenameFilter f=new FilenameFilter()
  43.    {
  44.      public boolean accept(File file, String name)
  45.       {
  46.         if(name.endsWith(".txt"))
  47.                   return true;
  48.           else
  49.                    return false;
  50.            }
  51.    };
  52.   File dir1=new File("."); //current directory
  53.   File[] files=dir1.listFiles(f);
  54.   if(files.length==0)
  55.         System.out.println("no files available with this extension ");
  56.     else
  57.       {
  58.          for(int i=0; i<files.length; i++)
  59.           {
  60.             for(File af:files)
  61.              {
  62.                t[i]=new search_engine(af.getName());
  63.                t[i].start();
  64.               }
  65.            }
  66.        }
  67.   }    
  68. }
c) Write a program that implements a multi-thread application that has three threads. First thread generates random integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of cube of the number
CODE
šŸ‘‡