- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we call run() method directly instead of start() in Java
Yes, we can do that. Let us see an example −
Example
class my_thread extends Thread{ public void run(){ try{ System.out.println ("The thread " + Thread.currentThread().getId() + " is currently running"); } catch (Exception e){ System.out.println ("The exception has been caught"); } } } public class Main{ public static void main(String[] args){ int n = 6; for (int i=1; i<n; i++){ my_thread my_object = new my_thread(); my_object.run(); } } }
Output
The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running The thread 1 is currently running
A class named ‘my_thread’ inherits the main Thread, wherein a ‘run’ function is defined, that gives the id of the current thread that is being run. A try and catch block is defined that catches an exception (if any) and displays the relevant error. In the main function, a ‘for’ loop is run and new object of the ‘my_thread’ class is created. The ‘run’ function is called on this object.
Advertisements