How to Create Threads in Java

How to Create Thread


There are two ways to Create Thread 


1 Extending Thread Class

public class ThreadClass extends Thread {

@Override

public void run() {

System.out.println("Thread Running Thread "+Thread.currentThread().getName());

}

}

2. Runnable Interface

public class RunnableClass implements Runnable {


@Override

public void run() {

System.out.println("Runnable Running Thread "+Thread.currentThread().getName());


}

}

Main Class how to Call the Thread and Runnable Threads

public class Main {


public static void main(String[] args) {

ThreadClass tClass = new ThreadClass();

tClass.start();

RunnableClass rClass = new RunnableClass();

Thread rThread = new Thread(rClass);

rThread.start();

}

}


   Both will Create the Similar Thread but there are some Advantages as Runnable Interface are

1. Less memory required for Runnable Interface

2. If a class is implementing the runnable interface then your class can extend another class.

3. When we extend Thread class, each of our thread creates unique object and associate with it. When we implements Runnable, it shares the same object to multiple threads.

 


 

Comments

Post a Comment

Popular posts from this blog

JunitTest

Log4j2 Setup