This section explain how to create thread by extending Thread class in java.
This section explain how to create thread by extending Thread class in java.This section explain how to create thread by extending Thread class in java.
Extending Thread :
You can create thread by extending Thread class and then by creating instance
of that class you can use it. Next extending class overrides the
run() method.
By calling super() method, initialize the thread in
its constructors. For beginning the execution of new thread call
start() method.
Example : In this example we are extending Thread class to create thread.
class ThreadClass extends Thread { ThreadClass() { } ThreadClass(String threadName) { super(threadName); System.out.println(this); start(); } public void run() { // Displaying info of current thread System.out.println(Thread.currentThread().getName()); } } public class ExtendThread { public static void main(String[] args) { Thread thread1 = new Thread(new ThreadClass(), "Hello Thread1"); Thread thread2 = new Thread(new ThreadClass(), "Hello Thread2"); Thread thread3 = new ThreadClass("Thread3"); Thread thread4 = new ThreadClass("Thread4"); /* call start() to start thread */ thread1.start(); thread2.start(); try { Thread.currentThread(); /* The sleep() method delay 1 second to main. */ Thread.sleep(1000); } catch (InterruptedException e) { } /* Print info of main thread */ System.out.println(Thread.currentThread()); } }
Output :
Thread[Thread3,5,main] Thread[Thread4,5,main] Thread3 Thread4 Hello Thread1 Hello Thread2 Thread[main,5,main]