Dremendo Tag Line

Thread Methods in Java

Thread in Java

In this lesson, we will learn about the most commonly used methods of Thread class and how to use them to control threads in java.

Thread Methods in Java?

There are several methods available in the Thread class, but here we will discuss the most commonly used methods of the Thread class and their uses in Java.

video-poster

run() and start() Method

In the run() method, we write the codes we want to execute in a thread, and the start() method is used to execute the code written in the run() method on a child thread.

Example

class ThreadA extends Thread
{
    public void run()
    {
        int i,j,fc;
        for(i=1; i<=10; i++)
        {
            fc=0;
            for(j=1; j<=i; j++)
            {
                if(i%j==0)
                {
                    fc++;
                }
            }
            if(fc==2)
            {
                System.out.println("Prime Number = "+i);
            }
        }
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        // execute the thread
        a.start();
    }
}

Output

Prime Number = 2
Prime Number = 3
Prime Number = 5
Prime Number = 7

sleep() Method

The sleep() method is used to pause the execution of a running thread for specified milliseconds (1000 milliseconds = 1 second). The thread starts running when the specified time for the sleep() method is over.

This method is used in a try-catch block because it raises the InterruptedException exception.

Example

class ThreadA extends Thread
{
    public void run()
    {
        int i;
        for(i=1; i<=5; i++)
        {
            System.out.println(i);
            try
            {
                // pause the thread for 2 seconds
                Thread.sleep(2000);
            }
            catch(InterruptedException e) {}
        }
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        // execute the thread
        a.start();
    }
}

Output

1
2
3
4
5

In the above program, we pause the child thread ThreadA for 2 seconds using the sleep() method, so each number on the output screen will appear after 2 seconds.

join() Method

The currently running thread is put into a wait state by the join() method until the thread on which the join() method was called has finished running.

This method is used in a try-catch block because it raises the InterruptedException exception.

Example

class ThreadA extends Thread
{
    public void run()
    {
        int i;
        for(i=1; i<=5; i++)
        {
            System.out.println(i);
            try
            {
                Thread.sleep(1000);
            }
            catch(InterruptedException e) {}
        }
        System.out.println("Exit from ThreadA");
    }
}

class ThreadB extends Thread
{
    public void run()
    {
        int i;
        for(i=10; i<=15; i++)
        {
            System.out.println(i);
            try
            {
                Thread.sleep(3000);
            }
            catch(InterruptedException e) {}
        }
        System.out.println("Exit from ThreadB");
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();
        ThreadB b = new ThreadB();

        // execute the thread
        a.start();
        b.start();
        try
        {
            a.join();
        }
        catch(InterruptedException e) {}
        System.out.println("End of main thread");
    }
}

Output

1
10
2
3
11
4
5
Exit from ThreadA
End of main thread
12
13
14
15
Exit from ThreadB

In the above program, we have invoked the join() method on the object of class ThreadA. The join() method puts the main thread into a wait state until the ThreadA has completed its execution.

isAlive() Method

The isAlive() method is used to check whether a thread is alive. This method returns true if the thread is alive and returns false if the thread is not alive.

Example

class ThreadA extends Thread
{
    public void run()
    {
        int i;
        System.out.println("Even numbers between 1 to 10");
        for(i=1; i<=10; i++)
        {
            if(i%2==0)
            {
                System.out.println(i);
                try
                {
                    // pause the thread for 2 seconds
                    Thread.sleep(2000);
                }
                catch(InterruptedException e) {}
            }
        }
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        // execute the thread
        a.start();
        System.out.println("Thread is alive: " + a.isAlive());
        try
        {
            a.join();
        }
        catch(InterruptedException e) {}
        System.out.println("Thread is alive: " + a.isAlive());
    }
}

Output

Thread is alive: true
Even numbers between 1 to 10
2
4
6
8
10
Thread is alive: false

getId() Method

The getId() method is used to get the ID number of a thread. The thread ID is a positive number generated when a thread is created. The thread ID is unique and remains unchanged during the lifetime of a thread. When a thread is terminated, the thread ID may be reused.

Example

class ThreadA extends Thread
{
    public void run()
    {
        System.out.println("Hello I am child thread");
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        // execute the thread
        a.start();

        System.out.println("Thread ID: " + a.getId());
    }
}

Output

Thread ID: 8
Hello I am child thread

setName() and getName() Method

The setName() method is used to set a new name of a thread. The getName() method is used to get the name of a thread.

Example

class ThreadA extends Thread
{
    public void run()
    {
        System.out.println("Hello I am child thread");
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        System.out.println("Thread Name: " + a.getName());
        a.setName("delta56");
        a.start();

        System.out.println("Thread Name: " + a.getName());
    }
}

Output

Thread Name: Thread-0
Thread Name: delta56
Hello I am child thread

getState() Method

The getState() method is used to get the state of a thread. The state means in which form the thread is working in the processor.

Example

class ThreadA extends Thread
{
    public void run()
    {
        System.out.println("Hello I am child thread");
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a = new ThreadA();

        System.out.println("Thread State: " + a.getState());
        a.start();
        System.out.println("Thread State: " + a.getState());

        try
        {
            a.join();
        }
        catch(InterruptedException e) {}

        System.out.println("Thread State: " + a.getState());
    }
}

Output

Thread State: NEW
Thread State: RUNNABLE
Hello I am child thread
Thread State: TERMINATED

setPriority() Method

The setPriority() method is used to set the running priority of a thread in the processor. There are three types of thread priority, and they are:

  • MIN_PRIORITY means minimum priority whose constant value is 1.
  • NORM_PRIORITY means normal priority whose constant value is 5.
  • MAX_PRIORITY means maximum priority whose constant value is 10.

Example

class ThreadA extends Thread
{
    public void run()
    {
        int i,j,fc,pc=0;
        for(i=1; i<=90000; i++)
        {
            fc=0;
            for(j=1; j<=i; j++)
            {
                if(i%j==0)
                {
                    fc++;
                }
            }
            if(fc==2)
            {
                pc++;
            }
        }
        System.out.println("ThreadA -> Total Prime Number = "+pc);
    }
}

class ThreadB extends Thread
{
    public void run()
    {
        int i,j,fc,pc=0;
        for(i=1; i<=90000; i++)
        {
            fc=0;
            for(j=1; j<=i; j++)
            {
                if(i%j==0)
                {
                    fc++;
                }
            }
            if(fc==2)
            {
                pc++;
            }
        }
        System.out.println("ThreadB -> Total Prime Number = "+pc);
    }
}

class ThreadC extends Thread
{
    public void run()
    {
        int i,j,fc,pc=0;
        for(i=1; i<=90000; i++)
        {
            fc=0;
            for(j=1; j<=i; j++)
            {
                if(i%j==0)
                {
                    fc++;
                }
            }
            if(fc==2)
            {
                pc++;
            }
        }
        System.out.println("ThreadC -> Total Prime Number = "+pc);
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a=new ThreadA();
        ThreadB b=new ThreadB();
        ThreadC c=new ThreadC();
        a.setPriority(1);
        b.setPriority(5);
        c.setPriority(10);
        a.start();
        b.start();
        c.start();
    }
}

Output

ThreadC -> Total Prime Number = 8713
ThreadB -> Total Prime Number = 8713
ThreadA -> Total Prime Number = 8713

In the above program, we created three threads that count the number of prime numbers between 1 and 90000. We set the priority of ThreadA's object to 1 (MIN_PRIORITY), ThreadB's object to 5 (NORM_PRIORITY), and ThreadC's object to 10 (MAX_PRIORITY).

Because the priority of the ThreadC is set to 10, which is the highest priority, it will get more time in the processor for its code execution. The ThreadB will get a normal amount of time in the processor for its code execution, and ThreadA will get a time below the normal time for its code execution.

If we run the above program several times, we can see that the ThreadC completes its execution first compared to the other two threads because it is getting more time in the processor for its code execution than the other two threads.

getPriority() Method

The getPriority() method is used to get the priority of a thread.

Example

class ThreadA extends Thread
{
    public void run()
    {
        System.out.println("I am ThreadA with MAX_PRIORITY");
    }
}

class ThreadB extends Thread
{
    public void run()
    {
        System.out.println("I am ThreadB with NORM_PRIORITY");
    }
}

public class Example
{
    public static void main(String args[])
    {
        ThreadA a=new ThreadA();
        ThreadB b=new ThreadB();

        a.setPriority(10);
        System.out.println("ThreadA priority: " + a.getPriority());
        System.out.println("ThreadB priority: " + b.getPriority());
        a.start();
        b.start();
    }
}

Output

ThreadA priority: 10
ThreadB priority: 5
I am ThreadA with MAX_PRIORITY
I am ThreadB with NORM_PRIORITY

Note: By default, the priority of a thread is 5 (NORM_PRIORITY) unless we set a new priority for the thread.