In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:
  1. Extending the java.lang.Thread Class
  2. Implementing the java.lang.Runnable Interface

Extending the java.lang.Thread Class

For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:

  1. Extend the java.lang.Thread Class.
  2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.
  3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.
  4. Invoke the start( ) method on the instance of the class to make the thread eligible for running.

By extend the Thread class of java.lang package.
Syntax………..

class MyThread extends Thread
{
-----------------;
-----------------;
}

Override the run( ) Method-The run( ) method has to be Overridden by writing codes required for the thread. The thread behaves as per this code segment.

public void run()
{
----------------;
----------------;
}

Commonly used Constructors of Thread class:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)

Commonly used methods of Thread class:

  • public void run(): is used to perform action for a thread.
  • public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
  • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  • public void join(): waits for a thread to die.
  • public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  • public int getPriority(): returns the priority of the thread.
  • public int setPriority(int priority): changes the priority of the thread.
  • public String getName(): returns the name of the thread.
  • public void setName(String name): changes the name of the thread.
  • public Thread currentThread(): returns the reference of currently executing thread.
  • public int getId(): returns the id of the thread.
  • public Thread.State getState(): returns the state of the thread.
  • public boolean isAlive(): tests if the thread is alive.
  • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
  • public void suspend(): is used to suspend the thread(depricated).
  • public void resume(): is used to resume the suspended thread(depricated).
  • public void stop(): is used to stop the thread(depricated).
  • public boolean isDaemon(): tests if the thread is a daemon thread.
  • public void setDaemon(boolean b): marks the thread as daemon or user thread.
  • public void interrupt(): interrupts the thread.
  • public boolean isInterrupted(): tests if the thread has been interrupted.
  • public static boolean interrupted(): tests if the current thread has been interrupted.

Extending Thread class Example

This is a way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.

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

class MyThreadDemo
{
   public static void main( String args[] )
   {
     MyThread mt = new  MyThread();
     mt.start();
   }
}

In this case also, as we must override the run() and then use the start() method to start and run the thread. Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object.
output:

What if we call run() method directly without using start() method ?
In above program if we directly call run() method, without using start() method,

public static void main( String args[] )
{
   MyThread mt = new MyThread();
   mt.run();
}

Doing so, the thread won’t be allocated a new call stack, and it will start running in the current call stack, that is the call stack of the main thread. Hence Multithreading won’t be there.

Can we Start a thread twice ?
No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.

public static void main( String args[] )
{
   MyThread mt = new MyThread();
   mt.start();
   mt.start();     //Exception thrown
}

When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown.

Implementing the Runnable Interface:
The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form,

public void run()
  • run() method introduces a concurrent thread into your program. This thread will end when run() returns.
  • You must specify the code for your thread inside run() method.
  • run() method can call other methods, can use other classes and declare variables just like any other normal method.
class MyThread implements Runnable
{
   public void run()
   {
     System.out.println("concurrent thread started running..");
   }
}

class MyThreadDemo
{
    public static void main( String args[] )
    {
      MyThread mt = new MyThread();
      Thread t = new Thread(mt);
      t.start();
   }
}

To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago