What are the two ways of creating threads and multiple threads in java? Provide sample code demonstrating these ways to create thread.
Posted by Nikheel Bhasmare on October 18th 2017 12:47 PM
Thread : Thread is path of execution which runs independently within the process. Process is nothing program in execution. Java is multi_threaded language because when JVM (Java Virtual Machine) starts execution of any application it also starts the execution of 2 threads : 1. main thread - it is responsible for invoking main method. 2. garbage collector - it is responsible for reclaiming unused memory of object. Ways of creating threads/multiple threads : Basically there are 2 ways of creating threads in java. 1. By extending Thread class. 2. By implementing Runnable interface. Java inherits variables and methods from parent class by extending a class. In this case we can inherit from only one parent class as multiple inheritance is not allowed in java. We can use interface implementation to overcome this limitation. 1. By extending Thread class. java.lang.* package contains the definition of thread class. In this method we need to extend the thread class. Steps – 1. Create a class and extend Thread class 2. Override the run() method. 3. Instantiate the class 4. Call start() method Check e.g. 1 from code : 2. By implementing Runnable interface : Steps : 1. Create a class and implement Runnable interface 2. Override the run() method 3. Instantiate the class 4. Call start() method Check e.g.2 from code :