There are two ways to create threads.
1. Create Threads implementing Runnable interface 2. Create Threads Extending Thread class
When to use Runnable interface
Use Runnable interface when your class is extending some other class. Since in Java mulitple inheritance is not possible we use Runnable interface to create Threads. class SomeClass When your class don't extend any other class extend Thread class and override the run method of Thread class and invoke start method to run a thread. class Myclass extends Thread If there is a situation that a class is to be executed as a thread then you can achieve this by implementing Runnable interface. You will need to follow three basic steps: STEP 1: Implement run method provided by Runnable interface. This method is executed when a start method is invoked. Syntax : public void run( ) Create a Thread object using any of the following constructors: Thread(Runnable threadObj, String threadName); or Thread(Runnable threadObj); STEP 3: Once Thread object is created, you can start it by calling start method, which executes a call to run method. Syntax : public void start() The following is a simple program which explains creation of threads using Runnable interface Thread with Runnable CODE class RunnableExample OUTPUT Created thread by implementing Runnable interface. DESCRIPTION In this example we created an object of type THINGS TO TRY
The class which creates threads should extend Thead class and override the run method. The will be much clear when you look at the below example. Creating Normal Thread CODE class MyThread extends Thread OUTPUT Created thread by extending Thread DESCRIPTION In the above program THINGS TO TRY
|