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, and it contains variables and methods which lives and dies on the heap. But a Thread of Execution is an individual process which has its stack call. Even if you don’t create any thread in your program, a thread will be running there, and main() method will start that.

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

Type of Thread

A thread can be of two kinds.

  • User Thread
  • Daemon Thread

Difference between these two type of thread is that JVM exit an application only when all User Thread is 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:

The class needs 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.

 The run method can be overloaded in class. But only run() method(without argument) will be considered by JVM. Any other overridden method will need to be called explicitly.

Implements runnable interface

The class needs to implement the runnable interface and override the run() method. Creating Thread in this way gives you the 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 need to be created before creating Thread of Execution.
Creating a Thread object is different for both the cases. In case of Extending Thread class, you can directly initiate class with the new keyword as it has extended Thread class itself.

MyThread t = new MyThread()

In case of implementing Runnable interface. First created runnable class needs to be instantiated.

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 the first case(Extending Thread class) But in case of Runnable Thread class needs to know that run method from class implementing runnable interface needs to be invoked instead of run() from Thread class. So we need to pass the class as an argument to Thread. A 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).

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.

The overloaded constructor in Thread class:

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

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

Till now Thread has two states.

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

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 the runnable state means Thread is created but it’s run method is not yet executed and the thread is waiting for his turn. Once Thread got selected thread’s run method will execute, and that state will be 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 only running thread. If a thread is not in a runnable state, then it cannot be selected 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 three states of Thread

  •  New
  •  Runnable
  •  Running

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

  • Waiting/blocked/sleeping
  • Dead

A thread is in the 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 a 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 a static method so it works only on currently running thread. Scheduler makes 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 nonstatic 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 until Thread A completes.

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 another way in which Thread can leave a running state and can return to Runnable state. run methods complete a call to wait()

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

Static lock
Nonstatic lock

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

Only methods/block can be synchronized not variable or class.
A class can have both synchronized/ synchronized method.
A thread could access synchronized block even if one Thread got the lock of given object.
If a thread goes to sleep, it holds any locks it has. A thread can have Lock of a 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.

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 a lock for a different thing(Object & class)

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

Cheat-sheet

  • A thread can be created by extending Thread Class and overriding the run() method.
  • A thread can also be created by Implementing Runnable interface and then calling Thread constructor that takes a Runnable argument.
  • start() method can be called on Thread Object only once.
  • Once start() method is called on Thread Object it becomes a thread of execution. Before start() method called it is said to be in the new state and is not considered alive.
  • There is no guarantee of the 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 cannot be started again.

16 Comments Java Thread Tutorial

  1. Sunilp

    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.

    1. Sunilp

      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.

  2. Sunilp

    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.

  3. Kavitha

    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.

  4. Mayur

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

  5. Damodar

    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… ?

Comments are closed.