Java Thread Tutorial

Thread term can be used in two ways

  • An instance of class java.lang.Thread
  • A Thread of Execution

An Instance of Thread is an object like any other object in Java, it contains variables and methods which lives and dies on the heap. But a Thread of Execution is an individual process  which has its own stack call. Even if you don’t create any thread in your program, thread will be running there and main() method will start that.

Note: In case of thread most of thing is unpredictable.

Type of Thread

Thread can be of two types.

  • User Thread
  • Daemon Thread

Difference between these two type of thread is that JVM exit an application only when all User Thread are complete. JVM doesn’t care about the status of Daemon Thread.

Thread Definition

A thread can be defined in two ways

  • Extend the java.lang.Thread class.
  • Implement the Runnable interface.

Extending Java Thread class:

Class need to extend the Thread class & Override the run() method.

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

But the problem with this approach is that class can not extend any more class.

Note : run method can be overloaded in class. but only run() method(without argument) will be consider by JVM. Any other overridden method will needs to be called explicitly.

Implements runnnable interface

Class needs to implement runnable interface and override the run() method. Creating Thread in this way gives you flexibility to extend any class you like.

class MyRunnable implements Runnable {

public void run() {

System.out.println("Important job running in MyRunnable");

} }

Instantiating Thread :

Every thread of execution begins as an instance of class Thread. In any case Thread objects needs to be created before creating Thread of Execution.
Creating Thread object is different for both the cases. In case of Extending Thread class you can directly initiate class with new keyword as it has extended Thread class itself.

MyThread t = new MyThread()

In case of implimenting Runnable interface. First created runnable class needs to be instatiated.

MyRunnable r = new MyRunnable();

Now pass this runnable object to Thread.

Thread t = new Thread(r);

If you create a thread using the no-arg constructor, the thread will call its own run(). This happened in first case(Extending Thread class) But in case of Runnable Thread class needs to know that run method from class implementing runnnable interface needs to be invoked instead of run() from Thread class. So we need to pass the class as argument to Thread. Single runnable instance can be passed to multiple Thread object.

public class TestThreads {

public static void main (String [] args) {

MyRunnable r = new MyRunnable();

Thread foo = new Thread(r);

Thread bar = new Thread(r);

Thread bat = new Thread(r);
}}

Giving the same target to multiple threads means that several threads of execution will be running the very same job (and that the same job will be done multiple times).

Note : The Thread class itself implements Runnable. (After all, it has a run() method that we were overriding.) This means that you could pass a Thread to another Thread’s constructor.

Overloaded constructor in Thread class:

Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)

Till now we have created Thread object and it knows what to do in form of run() method. But till now it is still an object. It does not have its own call stack. In other words Thread of execution has not been started. A Thread object will have its own stack only when start() method will be called on Thread.

Till now Thread has 2 states.

  • New state (Thread object created but Start method not invoked)
  • runnable(alive) state (start method is invoked )

Note : Calling run() method from java code directly mean that you are invoking a method and stack will not be created.

When a Thread is in runnable state means Thread is created but it’s run method is not yet executed and thread is waiting for his turn. Once Thread got selected thread’s run method will execute and that state will called running state.

Thread Scheduler :
The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. Some method that can influence scheduler to some extent(Note*: We can’t control the behavior of Thread scheduler)

These methods are from Thread class

* public static void sleep(long millis) throws InterruptedException
* public static void yield()
* public final void join() throws InterruptedException
* public final void setPriority(int newPriority)

Methods from Object class.

* public final void wait() throws InterruptedException
* public final void notify()
* public final void notifyAll()

Till now we come across 3 state of Thread

  •  New
  •  Runnable
  •  Running

There are some more state of thread in which Thread will not be eligible to run.

  • Waiting/blocked/sleeping
  • Dead

A thread is in Dead state when its run method completed its execution.

Sleeping
The sleep() method is a static method of class Thread. (where it still has to beg to be the currently running thread). as it is static method only currently running Thread will sleep. Syntax would be : Thread.sleep()

yield: yield method is related with the priority of Thread. It is also static method so it works only on currently running thread. Scheduler make it sure that If a thread enters the runnable state, and it has a higher priority than any of the threads in the pool and a higher priority than the currently running thread, the lower-priority running thread usually will be bumped back to runnable and the highest-priority thread will be chosen to run. at any given time the currently running thread usually will not have a priority that is lower than any of the threads in the pool. yield() is supposed to do is make the currently running thread head back to runnable to allow other threads of the same priority to get their turn.

Join()
Join is a non static method. It lets one thread “join onto the end” of another thread. If you join Thread B to Thread A Thread B will not start untill Thread A complets.

Syntax :

Thread t = new Thread();
t.start();
t.join();

takes the currently running thread and joins it to the end of the thread referenced by t

There are several other way in which Thread can leave running state and can return to Runnable state. run methods completes a call to wait()

Synchronize: It works with Lock. Lock is of two type.

Static lock
Non static lock

Note: There is only one lock per object. Once a thread got the lock of an object no other thread can enter the synchronise block/method of given object.

Only methods/block can be synchronised not variable or class.
A class can have both synchronised / non synchronised method.
Thread can access non synchronised block even if one Thread got the lock of give object.
If a thread goes to sleep, it holds any locks it has. A thread can have Lock of different object at the same time.

Syntax :

class SyncTest {

public void doStuff() {

System.out.println("not synchronized");

synchronized(this) {

System.out.println("synchronized");

}}}

Synchronised Static method :

There is only one copy of the static data, so you only need one lock per class to synchronize static methods—a lock for the whole class. There is such a lock; every class loaded in Java has a corresponding instance of java.lang.Class representing that class. It’s that java.lang.Class instance whose lock is used to protect the static methods of the class.

Syntax:

public static synchronized int getCount() {

return count;

}

MyClass.class thing is called a class literal. It tells the compiler (who tells the JVM): go and find me the instance of Class that represents the class called MyClass.

Note : Threads calling non-static synchronized methods in the same class will only block each other if they’re invoked using the same instance. As there is only one lock per instance. Threads calling static synchronized methods in the same class will always block each other— As there is only one lock per class.

A static synchronized method and a non-static synchronized method will not block each other. As they need lock for different thing(Object & class)

Note : join(), sleep(), yield() these methods keep locks. while wait release Lock.

Cheat-sheet

  • Thread can be created by extending Thread Class and overriding the run() method.
  • Thread can also be created by Implementing Runnable interface and then calling Thread constructor that takes Runnable argument.
  • start() method can be called on Thread Object only once.
  • Once start() method is called on Thread Object it becomes thread of execution. Before start() method called it is said to be in new state and is not considered alive.
  • There is no guarantee of order in which Thread will get executed after getting started.
  • We can influence the order in which Thread get executed by setting its(Thread) priority(1-10).
  • A running thread may enter blocked/waiting state by wait(), sleep or join() call.
  • A running thread may enter blocked/waiting state because it can’t acquire the lock of a synchronized block of code.
  • A dead thread can not be started again.
Series Navigation<< What is the use of serialVersionUIDJava Array Tutorial >>
By | 2012-04-20T19:14:31+00:00 April 20th, 2012|Core Java|16 Comments

About the Author:

16 Comments

  1. gowthaman October 29, 2012 at 9:29 am - Reply

    sir, i want to study java. could you please tell that how would be learning java….

  2. smartvilla April 16, 2013 at 5:54 am - Reply

    very nice

    • mahesh August 6, 2013 at 4:12 pm - Reply

      this is very nice tutorial for beginner

  3. Avdhesh samele January 2, 2014 at 9:45 pm - Reply

    its good information, well describe………..thnks

  4. Damodar January 13, 2014 at 11:56 am - Reply

    Suppose we have 10 thread and start this thread one by one then How to know which thread is terminated first then which thread is terminated sec and so on… ?

    • mayank singh March 12, 2014 at 9:34 am - Reply

      freind if the thread has terminated, the next thread will not execute

  5. surendra January 24, 2014 at 7:53 am - Reply

    your tutorial is very clear to understand. good job
    thank you guys

  6. Mayur July 5, 2014 at 5:57 am - Reply

    When the thread is in running state… it has to be when the thread is in runnable/ready state…

  7. Kavitha October 21, 2014 at 8:08 pm - Reply

    u wrote running state instead of runnable state below the line Note: Calling run() method from java…….. i think it is runnable but i dont know exactly.

  8. Sunilp January 21, 2015 at 6:02 pm - Reply

    Typo:

    exists –> exits
    “Difference between these two type of thread is that JVM exists an application only when all User Thread are complete.”

    Thanks for our service. Your tutorials are simple & clear.

  9. Sunilp January 21, 2015 at 6:07 pm - Reply

    one more typo:

    When a Thread is in running state means Thread’s run method is not yet executed and thread is waiting his turn. –> When a Thread is in new state means Thread’s run method is not yet executed and thread is waiting his turn.

    • Sunilp January 21, 2015 at 6:11 pm - Reply

      Sorry typo in my comment.. 🙂

      When a Thread is in running state means Thread’s run method is not yet executed and thread is waiting his turn. –> When a Thread is in runnable state means Thread is created but it’s run method is not yet executed and thread is waiting his turn.

      • Vivekanand Gautam January 24, 2015 at 5:59 am - Reply

        Error resolved. Thanks

  10. Swati November 3, 2015 at 12:18 pm - Reply

    Hey,Your Tutorial is very simple,usefull and easy to understand.Thank you.

  11. laxmi November 11, 2015 at 2:40 pm - Reply

    U have done a great job …

  12. stephen June 29, 2016 at 5:19 am - Reply

    This tutorial is very excellent

Leave A Comment