Thread Basics

Related Examples

Java defines two way to create thread

  1. You can extends the Thread class.
  2. You can implement the Runnable interface.

First Way :

    Extends the Thread class -

 

// Extend Thread class
class NewThread extends Thread
{
    // constructor called when create NewThread Object
    NewThread(){
    
       //Create a new thread
         super("Thread name");
         
         // start thread and after call start method run method will call automaticaly
         start();
       
    }
 
    public void run()   // Called when start() called
    {
        try{
               
               // Do here long running operations
                   
           }catch(Exception e){
        
           }
    }
}

 

    // Create NewThread Class Object
     Thread nThread = new NewThread();

 

Second Way :

Implement Runnable Interface -

 

// Extend Thread class
class NewThread implements Runnable
{
     // Thread Reference
     Thread t;

    // Constructor called when create NewThread Object
    NewThread(){
    
       // Create a new thread
         t = new Thread(this,"Thread name");
         
         // start thread and after call start method run method will call automaticaly
         t.start();
       
    }
 
    public void run()   // Called when start() called
    {
        try{
               
               // Do here long running operations
                   
           }catch(Exception e){
        
           }
    }
}
 

 

     // Create NewThread Class Object
     Thread nThread = new NewThread();

 

Which Thread Way Used And When -

 

    1.  Some time required to extends some other class and also want to use thread , In this case we will implements runnable and create thread , beacause we can not extends multiple classes.

    2.  Otherwise we will extends Thread class and create thread .

 

Inner class way to create thread without creating class.

 

public void onClick(View v) {
        new Thread(new Runnable() {
            public void run() {
            
                // Do here long running operations
                final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
                  
            }
        }).start();
    }