
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between Thread.start() and Thread.run() in Java.
As we know that start() and run() are the two important methods of multithreading and one is used to create a new thread while other is used to start executing that thread.
Following are the important differences between Thread.start() and Thread.run().
Sr. No. | Key | start() | run() |
---|---|---|---|
1 | Implementation | start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. | While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place. |
2 | Definition | start method is defined in thread class and its package is java.lang. | run is a method of Runnable interface and also define in java.lang package |
3 | Invocation | start method can't be invoked more than once on same object otherwise it will throw java.lang.IllegalThreadStateException. | run method on other hand do not throws any type of exception if it is being get called more than once.So multiple invocation is possible in case of run method. |
4 | Number of threads | As already stated that in case of calling start method a new thread is created along with the current thread so atleast two threads are there and hence multithreading is introduced. | On other hand in case of direct calling of run method no new thread is created and task is made to be executed on same current thread so only one thread is there and hence no multithreading is introduced. |
5 | Calling | As thread class implements Runnable interface so it implementing its run method also in such a way that start method internally called run method after creating a new thread. | On other hand run method executed by start method or get called directly if we implement Runnable interface and call run method. |
Example of Thread.start() vs Thread.run()
JavaTester.java
public class JavaTester extends Thread{ public void run(){ System.out.println("Thread is running..."); } public static void main(String args[]){ JavaTester t1=new JavaTester(); // this will call run() method t1.start(); } }
Output
Thread is running...
Example
JavaTester.java
public class JavaTester implements Runnable{ public void run(){ System.out.println("Thread is running..."); } public static void main(String args[]){ JavaTester m1=new JavaTester(); Thread t1 =new Thread(m1); // this will call run() method t1.start(); } }
Output
Thread is running...
Advertisements