Square CSS

Thursday, November 1, 2018

Java Multithreading : Implements Runnable Vs Thread Class

In Java we can create a thread in two ways :

  • By extending Thread class.
  • By implementing the Runnable interface.

Difference between  Implements Runnable and Thread Class :


Since by extending Thread class we cannot inherit other classes. But in the case of Runnable Interface, we can implement as many interfaces as much as required.

When we create a thread using Thread class each time a new object is created. But in the case of the Runnable interface, it uses the same object for multiple threads.

The Runnable interface is preferred over the Thread class because of the above reasons.


Creating thread using Thread Class :


For creating a thread using Thread class extend the Thread class. Provide the code in run() method. Create the thread using new operator and call the start() method of Thread class.
      

      
        


     

class PlayExt extends Thread{    

     public void run(){
           // code to execute 
      }

}

public class
MyExtend {
      public static void main(String[] args) {     
            PlayExt pe = new PlayExt
();
            // create object using new operator            

            pe.start();
            // call the start method to run a thread       

      }
}



Creating thread using Runnable Interface :


For creating a thread by implementing the Runnable interface. Provide the code in run() method. Create the thread by providing the class which implements the Runnable interface in the constructor of Thread class and call the start() method of Thread class.

             
      


      
        


     

// can extend other class also
class PlayRun implements Runnable{     

     public void run(){
           // code to execute 
      }

}

public class
 MyRunnable {
      public static void main(String[] args) {       
            Thread pr = new Thread(new PlayRun());
             
// provide the  in the constructor of Thread class
            pr.start();
            // call the start mentod to execute thread
       }
}





Refer the video tutorial :





                    In multithreading, synchronization is used to allow only one thread at a time to ... 


No comments:

Post a Comment

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts