How to create thread

Java threads are objects like any other Java objects. Threads are instances of class java.lang.Thread, or instances of subclasses of this class. In addition to being objects, java threads can also execute code. In this Java thread tutorial I will explain how to create and start threads.

Creating and Starting Threads

Creating a thread in Java is done like this:

Thread thread = new Thread();

To start the Java thread you will call its start() method, like this:

thread.start();

This example doesn't specify any code for the thread to execute. The thread will stop again right away after it is started.

There are two ways to specify what code the thread should execute. The first is to create a subclass of Thread and override the run() method. The second method is to pass an object that implements Runnable (java.lang.Runnable to the Thread constructor. Both methods are covered below.

There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface.
Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Thread Subclass

The first way to specify what code a thread is to run, is to create a subclass of Thread and override the run() method. The run() method is what is executed by the thread after you call start(). Here is an example of creating a Java Thread subclass:

public class MyThread extends Thread { public void run(){ System.out.println("MyThread running"); } }

To create and start the above thread you can do like this:

MyThread myThread = new MyThread(); myTread.start();

The start() call will return as soon as the thread is started. It will not wait until the run() method is done. The run() method will execute as if executed by a different CPU. When the run() method executes it will print out the text "MyThread running".

You can also create an anonymous subclass of Thread like this:

Thread thread = new Thread(){ public void run(){ System.out.println("Thread Running"); } } thread.start();

This example will print out the text "Thread running" once the run() method is executed by the new thread.

Commonly used Constructors of Thread class:
  1. Thread()
  2. Thread(String name)
  3. Thread(Runnable r)
  4. Thread(Runnable r,String name)
Commonly used methods of Thread class:
  1. public void run(): is used to perform action for a thread.

  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

  4. public void join(): waits for a thread to die.

  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

  6. public int getPriority(): returns the priority of the thread.

  7. public int setPriority(int priority): changes the priority of the thread.

  8. public String getName(): returns the name of the thread.

  9. public void setName(String name): changes the name of the thread.

  10. public Thread currentThread(): returns the reference of currently executing thread.

  11. public int getId(): returns the id of the thread.

  12. public Thread.State getState(): returns the state of the thread.

  13. public boolean isAlive(): tests if the thread is alive.

  14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.

  15. public void suspend(): is used to suspend the thread(depricated).

  16. public void resume(): is used to resume the suspended thread(depricated).

  17. public void stop(): is used to stop the thread(depricated).

  18. public boolean isDaemon(): tests if the thread is a daemon thread.

  19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

  20. public void interrupt(): interrupts the thread.

  21. public boolean isInterrupted(): tests if the thread has been interrupted.

  22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable Interface Implementation

The second way to specify what code a thread should run is by creating a class that implements java.lang.Runnable. The Runnable object can be executed by a Thread.

Here is a Java Runnable example:

public class MyRunnable implements Runnable { public void run(){ System.out.println("MyRunnable running"); } }

To have the run() method executed by a thread, pass an instance of MyRunnable to a Thread in its constructor. Here is how that is done:

Thread thread = new Thread(new MyRunnable()); thread.start();

When the thread is started it will call the run() method of the MyRunnable instance instead of executing it's own run() method. The above example would print out the text "MyRunnable running".

You can also create an anonymous implementation of Runnable, like this:

Runnable myRunnable = new Runnable(){ public void run(){ System.out.println("Runnable running"); } } Thread thread = new Thread(myRunnable); thread.start();
Subclass or Runnable?

There are no rules about which of the two methods that is the best. Both methods works. Personally though, I prefer implementing Runnable, and handing an instance of the implementation to a Thread instance. When having the Runnable's executed by a thread pool it is easy to queue up the Runnable instances until a thread from the pool is idle. This is a little harder to do with Thread subclasses.

Sometimes you may have to implement Runnable as well as subclass Thread. For instance, if creating a subclass of Thread that can execute more than one Runnable. This is typically the case when implementing a thread pool.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:

  • A new thread starts(with new callstack).

  • The thread moves from New state to the Runnable state.

  • When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class
class Multi extends Thread { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi t1=new Multi(); t1.start(); } }


Output:
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable { public void run() { System.out.println("thread is running..."); } public static void main(String args[]) { Multi3 m1=new Multi3(); Thread t1 =new Thread(m1); t1.start(); } }


Output:
Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitly create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.




Instagram