Multithreading in JAVA

Multithreading in JAVA

A thread is basically lightweight and the smallest unit of processing.  Threads use a shared memory area, hence they don't allocate separate memory area, therefore saves memory. Multiple threads which are executed simultaneously is called as multithreading.

In JAVA, one thread is always executed which is the main() thread.

Real World Example

First let's take an analogy, you might be reading this text as well as listening to music or eating, hence you are performing multiple tasks simultaneously. Now, let’s suppose we have an online banking system, where people can log in and access their account information. Whenever someone logs in to their account online, they receive a separate and unique thread so that different bank account holders can access the central system simultaneously.

Let's take a program showing multithreading,

class MultithreadingExample extends Thread
{ 
    public void run()
    { 
        for(int i=1;i<=3;i++)
        { 
            System.out.println(Thread.currentThread().getName()+" is running: "+i+" ");
            try{ 
                Thread.sleep(1000);
            } 
            catch(InterruptedException e){} 
        }
    }
}
class Main
{
    public static void main(String args[])
    { 
        MultithreadingExample obj1=new MultithreadingExample(); 
        MultithreadingExample obj2=new MultithreadingExample();
        obj1.setName("Thread-1"); 
        obj2.setName("Thread-2"); 
        obj1.start();
        obj2.start(); 
    } 
}

Output

Multithreading_Example_Output

In the above program, we can see from the output that the two threads thread-1 and thread-2 are executing simultaneously. The two threads have their own stack with their run() method, which is why we see the two threads running simultaneously, thereby demonstrating the multithreading process.

Creating a Thread

There are two ways of creating a thread :-

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

1. Example for creating a thread by Extending the Thread Class

Program(Save as Main.java)

class Multithreading extends Thread
{ 
    public void run()
    { 
        for(int i=1;i<=3;i++)
        System.out.println(i); 
     } 
}
class Main
{
    public static void main(String args[])
    { 
        Multithreading obj=new Multithreading();         
        obj.start(); 
    } 
}

Output

javac Main.java
java Main
1
2
3

We can see two new methods start() and run(), the start() method is invoked for the object created of the Thread class. The start() method makes the run() method of that class to be executed.

The program ends when the run() method ends.

2. Example for creating a thread by Implementing the Runnable Interface

Program(Save as Main.java)

class Multithreading implements Runnable
{ 
    public void run()
    { 
        for(int i=1;i<=3;i++)
        System.out.println(i); 
     } 
}
class Main
{
    public static void main(String args[])
    { 
        Multithreading obj=new Multithreading(); 
        Thread t1 = new Thread(obj);
        t1.start(); 
    } 
}

Output

javac Main.java
java Main
1
2
3

In the above program we need to pass the Runnable object(obj) as parameter for reference to the thread class, since the Runnable interface in java does not include the start() method, while the start() method is supported by the Thread class.

To check the methods supported by Runnable type in command prompt javap java.lang.Runnable

To check the methods supported by Thread class type in command prompt javap java.lang.Thread

Thread Methods

Method Description
setName() To change the name of the current thread.
getName() To retrieve the name of the thread
setPriority() To set the priority of a thread.
getPriority() To retrieve the priority of a thread.
Thread.currentThread() Returns the reference to the currently executing thread object
Thread.sleep() Causes the currently executing thread to pause for a specified time in milliseconds
isAlive() Returns a boolean value, true if thread is alive, else false.
join() Holds the execution of currently running thread until the specified thread has finished execution or terminated.
getState() Returns the state of the thread.

Share Me!