Java Threads

Java Thread Creation

 

We can define a thread in 2 ways :

 

1) Extend Thread class

2) Implement the Runnable interface

 

 

Extend Thread class:

 

This approach involves 2 steps :

 

1) Extend the java.lang.Thread class

 

2) Override the run() method

 

For example,

 

package com.javatutorial;

public class MyThread extends Thread {
  
  public void run(){
    System.out.println("MyThread running");
  }

}


Issue with this approach is since you are already extending Thread class, you won’t be able to extend another class.

 

Here is how to instantiate your Thread class in this scenario :

 

MyThread t1 = new MyThread();

 

Implementing Runnable interface

 

This approach lets you extend any other class you want while still implementing thread behavior.

package com.javatutorial;

public class MyRunnable implements Runnable {
  
  public void run(){
    System.out.println("My Runnable");
  }

}


 

For instantiating a thread in this approach, you need to instantiate your runnable class and then provide the Runnable instance to a Thread as shown below :

 

MyRunnable r = new MyRunnable();
Thread t = new Thread(r);

 

 

Running a Thread :

 

To start a Thread created using either of the approaches above, call its start() method.

i.e,

t.start();

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags