How multitasking or multi-threading is working in Java

Java supports the multi tasking concept using time sharing concept of CPU. It switch from one task to another task in the midway. We can control the switching time using sleep or wait method.
It's a totally random process, we cannot predict the order.


Screenshot/Output:

Using the try block (sleep method)

Without using the try block (sleep method)


The Code:



class Demo1 extends Thread
{
 public void run() 
 {
  for(int i=0;i<10;i++)
  {
   System.out.println("Thread 1  "+i);
   /*try
   {
    Thread.sleep(200);
   }
   catch(InterruptedException e)
   {
    System.out.println(e);
   }*/
  } 
 }
}

class Demo2 extends Thread
{
 synchronized public void run()         
 {
  for(int i=0;i<20;i++)
  {
   System.out.println("\t.\t Thread 2  "+i);
   /*try
   {
    Thread.sleep(100);
   }
   catch(InterruptedException e)
   {
    System.out.println(e);
   }*/
  }
 }
}

class Demo3 extends Thread
{
 public void run()
 {
  for(int i=0;i<30;i++)
  {
   System.out.println("\t.\t.\t.\t Thread 3  "+i);
   /*try
   {
    Thread.sleep(300);
   }
   catch(InterruptedException e)
   {
    System.out.println(e);
   }*/
  }
 }
}

public class myclass
{
 public static void main(String arg[])
 {
  Demo1 d1 = new Demo1();
  d1.start();
  Demo2 d2 = new Demo2();
  d2.start();
  Demo3 d3 = new Demo3();
  d3.start();
  
  for(int i=0;i<50;i++)
  {
   System.out.println("\t.\t.\t.\t.\t.\t MainThread  "+i);
   /*try
   {
    Thread.sleep(400);
   }
   catch(InterruptedException e)
   {
    System.out.println(e);
   }*/
  }
 }
}

/*Remove the comment tags and include the code and see what happens..*/
/*Its totally random output without synchonization.. run 2 3 time and see the different combinations*/

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Hackerrank String Reduction Solution

Bit Stuffing Code Implementation in Java