Blog Image

Threads in java  

This blog i am explaining about the thread.what is the thread ,how many ways we can create a thread ,which methods are there for getting a thread name ,priorities and life cycle  with a sample example explaining.

A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class.
We can define a Thread in the following 2 ways.

  1. By extending Thread class.
  2. By implementing Runnable interface.
A Thread can be created by extending Thread class also. But Java allows only one class to extend, it wont allow multiple inheritance. So it is always better to create a thread by implementing Runnable interface. Java allows you to implement multiple interfaces at a time.
Without executing Thread class start() method there is no chance of starting a new Thread in java.
life cycle of the Thread:

  • After creating a thread now thread is new start when we call start() method thread will be entered into ready state .
  • Thread Scheduler(TS) will allocates cpu for each and every thread ,if cpu allocation is happen for a thread  now it will be entered into running state.
  • After completing the run() method thread will entered into dead state.
see the below example for creating a thread using (extending thread and implementing for Runnable interface),

public class MainThread extends Thread {
    public void run()
    {
        for(int i=0;i<5;i++)
        {
            System.out.println("chaild Thread is called");
        }
       
    }
   /** using Runnable interface**/
public class SJGRunnable implements Runnable {

    public void run() {
        System.out.println("sjg runnable is calling");
    }

}
public class ThreadProgram {
    public static void main(String[] args) throws InterruptedException {
    /** calling Main thread class**/
        /*MainThread mt=new MainThread();//Instantiation of a Thread
        mt.start();*/
            /** calling SjgRunnable class **/
        SJGRunnable sjr=new SJGRunnable();
        Thread t =new Thread(sjr);
        t.start();
        for(int i=0;i<5;i++)
        {
        System.out.println("chaild thread");
        }
    }


After starting a Thread we are not allowed to restart the same Thread once again otherwise we will get runtime exception saying "IllegalThreadStateException". see below

public class ThreadProgram {
    public static void main(String[] args) throws InterruptedException {
        SJGRunnable sjr=new SJGRunnable();
        Thread t =new Thread(sjr);
        t.start();
        t.start();
        for(int i=0;i<5;i++)
        {
        System.out.println("chaild thread");
        }
    }

output:

Exception in thread "main" sjg runnable is calling
java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Unknown Source)
    at com.sjg.thread.ThreadProgram.main(ThreadProgram.java:10)

Every thread will have name and priority ,so we can get and we can set the name and priority of a thread
Thread will have name it may be explicitly provided the by the programmer or automatically jvm will generate the name, same way thread priority also.
Thread priorities are 1 to 10 where 1 is the least priority and 10 is highest priority.Based on this priorities only Thread Scheduler will allocates the cpu.
Thread which is having highest priority it will execute first ,if two threads will have same priority then we can't except exact execution order it depends on thread scheduler.
 See below example for setting and getting the name ,priority of a thread,

public class MainThread extends Thread {
    public void run()
    {
        for(int i=0;i<5;i++)
        {
            System.out.println(Thread.currentThread().getName());
            System.out.println("priority :"+Thread.currentThread().getPriority());
            System.out.println("main Thread is called");
        }
       
    }
}

public class ThreadProgram {
    public static void main(String[] args) throws InterruptedException {
        MainThread mt=new MainThread();
        MainThread mt1=new MainThread();
        mt1.setPriority(7);
        mt.start();
        mt1.start();

        System.out.println(Thread.currentThread().getName());
        mt1.currentThread().setName("examplethread");
        System.out.println(mt1.getName());
        System.out.println("priority in threadprogram :"+Thread.currentThread().getPriority());
        for(int i=0;i<5;i++)
        {
        System.out.println("child thread");
        }
    }

}


Thread-0
main
Thread-1
priority :7
main Thread is called
Thread-1
priority :7.....
main Thread is called
priority :4
main Thread is called
Thread-0
priority :4..........
main Thread is called
Thread-1
priority in threadprogram :5
child thread
child thread.....


You can download  above maven example from the attachments given below

About author

User Image
sagarreddy

my self is SagarReddy. I from bhadrachalam and i am working StackSpace software solutions pvt. Ltd. has a java developer. Learning the new things from authors to update my self to build my career Better Way.

0

-Comments

Be the first person to write a comment for this Blog
Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.