English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
There are two methods to create a new execution thread. One is to declare a class as a subclass of the Thread class. This subclass should override the run method of the Thread class. Then, you can allocate and start an instance of the subclass.
Another method to create a thread is to declare a class that implements the Runnable interface. Then, the class implements the run method. Then, an instance of the class can be allocated, passed as a parameter when creating Thread, and started.
Each thread has a name for identification. More than one thread may have the same name. If a name is not specified when creating a thread, a new name will be generated for it.
Serial number | Key | Line | Runnable |
---|---|---|---|
1 | Basic | Thread is a class. Used to create threads | Runnable is a functional interface used to create threads |
2 | Methods | It has multiple methods, includingstart() andrun() | It has only abstract methods run() |
3 | Each thread creates a unique object and is associated with it | Multiple threads share the same object. | |
4 | Memory | More memory required | Less memory required |
5 | Limitations | Java does not allow multiple inheritance, so a class that extends the Thread class cannot extend any other class | If a class is implementing the Runnable interface, then your class can extend another class. |
class RunnableExample implements Runnable{ public void run(){ System.out.println("Thread is running for Runnable Implementation"); } public static void main(String args[]){ RunnableExample runnable=new RunnableExample(); Thread t1 =new Thread(runnable); t1.start(); } }
class ThreadExample extends Thread{ public void run(){ System.out.println("Thread is running"); } public static void main(String args[]){ ThreadExample t1=new ThreadExample(); t1.start(); } }