Friday 16 December 2016

Multi Threading in Java Demonstration by Tortoise and Hare Story

Multithreading in Java gives the ability to execute code by different threads to perform tasks in parallel or as a separate task without waiting for other to complete.Computer games are the best examples of the Multithreading concept. The ability to make different objects act on a platform is enabled with the concept of Multithreading.

We can Create Threads in 2 ways:

1.) By Extending Thread Class

class MyClass extends Thread
{

public void run()
{

for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getId() + " Value : "+i);

}

// Running Concureency 
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block       
e.printStackTrace();
}
}

}


public class CreateThreadByExtendingClass 
{
  public static void main(String args[])
  {
MyClass m1 = new MyClass();
m1.start();

MyClass m2 = new MyClass();
m2.start();


  }

}

2.) By Implementing Runnable Interface

class myclass extends Thread
{
@Override
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getId() + " Value : "+i);

}
// Running Concureency 
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block       
e.printStackTrace();
}
}

}

public class CreateThreadByImplementRunnable 
{
public static void main(String args[])
 {
MyClass m1 = new MyClass();
m1.start();

MyClass m2 = new MyClass();
m2.start();

 }

}

-- Thread Without Extra Class

public class CreateThreadwithoutExtraClass 
{
private static int count=0;

public synchronized static void count()
{
count++;

}

public static void main(String args[])
{

Thread t1 = new Thread (new Runnable(){

@Override
public void run() {

for(int i=0;i<10000;i++)
{
count();
}
}
});

Thread t2 = new Thread (new Runnable(){

@Override
public void run() {

for(int i=0;i<10000;i++)
{
count();
}

}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println( " Value : " +count);


}

}

Tortoise and Hare Demonstration using Multi Threading in Java

Consider a Race where two threads race to complete a 100 meters distance. Given below is the implementation of Race example:
A player is considered as Racer and the class implements Runnable Interface which indicates to Threads that its run method is implemented in Racer class.

This class makes the thread to iterate for 100 times and for each iteration, it checks if some one has won the race and if already a Thread won the race, then the other quits.



RacerDemo.java

package TortoiseHareStoryImplementation;

public class Racer implements Runnable 
{
    public static String winner;

    public void race()
    {
for(int distance=1;distance <= 100;distance++)
{

System.out.println("Distance Covered by "+Thread.currentThread().getName()+ "is:"+distance +"meters");

boolean isRaceWon = this.isRaceWon(distance);

if(isRaceWon)
{
break;
}
}
}

private boolean isRaceWon(int totalDistanceCovered)
{
boolean isRaceWon =  false;

if((Racer.winner==null )& (totalDistanceCovered==100))
{
String winnerName = Thread.currentThread().getName();
Racer.winner = winnerName; //setting the winner name
System.out.println("Winner is :"+Racer.winner);
isRaceWon = true;
    }

else if(Racer.winner==null)
{
isRaceWon = false;
}
else if(Racer.winner!=null)
{
isRaceWon = true;
}
return isRaceWon;
}

@Override
public void run()
{
this.race();

}

}



RacDemo.java

package TortoiseHareStoryImplementation;

public class RaceDemo 
{
public static void main(String[] args)
{
Racer racer = new Racer();

Thread tortoiseThread = new Thread(racer, "Tortoise");
Thread hareThread = new Thread(racer, "Hare");

//Race to start. tell threads to start
tortoiseThread.start();
hareThread.start();

}

}


Output:







1 comment: