Posts

Showing posts with the label how to create custom thread in java with example

how to create our own thread in java with example

To create user defined thread in java, create a class that extends Thread or implements Runnable interface. Both of the Thread class and Runnable interface are available in java.lang package. class MyClass extends Thread OR class MyClass implements Runnable         •   Now in this class, write a run() method as, public void run (){ statements ; }        by default, this run() method is recognised and executed by a thread when you started a thread.        •    Create an object of MyClass, So that the run() method is available for execution. MyClass obj = new MyClass ();       •    Now, Create a thread and attach the thread to the object obj. Thread t = new Thread ( obj );       •    Run the thread. For this purpose, we should use start() method of Thread class. t . start ();          Now, the thread will start execution on the object of MyClass. In that object, run() method is found, henc