Thread is a process and it is a part of a program.

Thread is a class in java and is independent flow of excecution.

Which executes the actions or code written by the programmer. When we write a program with group of statements then those group of statements will excecuted one by one by the JVM, this flow of execution is called a thread.

Main thread wil always run internally by default in a java program

Difference between program and Thread


  • Each program contains its own data and own memory address
  • It is a independent application process


  • A thread is a process of executing instructions that can run independently of other threads.
  • Thread is called “light weight process”. It is beacause of the reason that is all the threads will share memory space or data and code among them self.
  • Every thread will have its own flow (i.e.) a separate path of execution.
  • Every program will have main thread which is nothing but, whenever the java program is running by giving java filename, then the class is loaded into the memory and JVM starts the thread. Since the each and every program execution starts from main method so the thread also starts execution from main method. This is why; thread is called as main thread.
  • Thread will have its own stack trace which tells the flow of program execution. Local variables are stored in stack and global variables are stored in heap memory.
  • More than one independent tasks are performed at a time within a program is called multithread.
  • +
  • By using Multi threading throughput increase i.e., performance is increasing.
  • Another advantage of using multithreading is that utilization of time in an optimum way.
  • We can not create a Thread again by using the same instance variable.
  • Stack will help to individual flow of execution or parallel flow of excecution (i.e.) nothing but multiple threads will run simultenously


  • The name itself will explain that two independent programs are running at a time is called Multiprocess or multitasking.
  • In multitasking or multithread at a time two two or more tasks wll be given to the processor which increases the efficiency of the program.
  • It is a Heavy weight process because it does not share the memory.
  • Every process will have its own memory.
sharing memory in threads

The above diagram shows two applications are stored in different memory locations i.e., App1 is stored on 1001 location and App2 is stored in 1002 location.

public class Thread1 { int j=10; public static void main(String[] args) { Thread1 t1 = new Thread1(); int i=10; m(); System.out.println(i); } public static void m() { int j=20; m1(); System.out.println(j); } public static void m1() { int k=30; Thread t = new Thread(); t.start(); m3(); } public static void m3() { System.out.println("Hello World"); } }
Execution of main method

In the given code, the program is having a main method() main thread which is invoking another method “m()” . The main thread will maintain the stack trace as main thread with the execution of main method. And m () invoking another method i.e.,m1() .

  • If the invoked method is creating a thread and starting the thread then the thread will have the separate stack trace because the m1() is again creating a thread.
  • So, each and every thread in the program maintains its own stack trace meaningfully its own execution flow.
  • JVM is going to terminate only when all the threads are executed (i.e) user defined threads.
  • Technically, thread is an instance of “Thread” class .
  • If there is no user thread running JVM will shutdown .
  • If there is no user thread running at that time JVM will not shutdown. All user threads are not running then that time JVM will shutdown.
  • Every main thread will contain a Boolean value that contain setter and getter methods and they executes in parallel.
  • In user threads daemon value is false(default)
  • In user threads daemon thread is true.

How to create threads in Java?

We can create threads by using the following two ways:
  1. Extending a thread
  2. Implements thread
Differe between extending thread and implements runable:

When we use Extending thread then we can not able to extend another class.

This is because of the reason as java does not allow multiple inheritance.

So the scope of extending the another class is not possible in case of this Extending a thread.

Ex: class MyThread extends Thread, AnotherClass //invalid

Where as when we use Implements runable here in this case we can able to extend another class.

So with this we can say that in case of Implements Runnable the scope of extending another class is possible.

It is more advisable when the user wants to access the another class features while using threads.

Ex: class MyThread extends Another class Implements Runnable //valid

1. Extending a thread:

Extending a thread is a user defined thread. Thread is a independent process of a program to execute a piece of code and override run() method

Here these are following the steps for extending a Thread

  • Extend a thread i.e., Subclass of a Thread
  • Override a run() method in subclass within the Thread class
  • Create a instance for Thread
  • Thread instance.start ().

/* program for Extending a Thread*/

public class Company Share extends Thread{ private String companyName; public CompanyShare(String cName){ companyName = cName; } @Override public void run() { System.out.println(companyName);; } } public class ThreadTest { public static void main(String[] args) { String companyNames[] = new String[3]; companyNames[0] = "com"; companyNames[1] = "com1"; companyNames[2] = "com2"; for(String cName:companyNames) { CompanyShare csh = new CompanyShare(cName); csh.start(); } System.out.println ("Main Thread is Executed"); } }

In the above example we get output as com , com 2,com1, Main Thread is Executed. Here first we take String array in that we store 3 company names and after that we create instance of a Company Share threads by passing cName then calling start() when we call start method at that time the run() will be executed first after that man thread is running.

  • t.start() – when thread is started it executed run().
  • without t.start() – directly executes the run() here new thread is not created. It is run on the Main Thread.
  • with t.start() – when created a new thread parallel run() i.e., it executes the logic which is their in the run().

2. implements runnable:

Runnable is an interface and it can contains only one method i.e.,nothing but run()

Here first we create a class it implements Runnable.

  • Override run() method.
  • Implementing logic for run ()
  • Create Runnable instance
  • Creating an instance to a thread and pass the value or instance for Runnable.
  • Thread t =new Thread();
  • t.start();
public class MyThread implements Runnable { @Override public void run(){ System.out.println ("Started"); m1(); } public void m1() { System.out.println ("m1"); m2(); System.out.println ("m2 completed"); } public void m2() { System.out.println ("m2"); } } public class RunThread { public static void main(String[] args) { System.out.println("Main Thread"); MyThread mt = new MyThread(); mt.start(); m4(); System.out.println("complted"); } public static void m4(){ Syste.m.out.println("m4");}}

Daemon Thread:

Daemon thread is a thread that runs for the benefit of other threads. These threads will run continuously and excecutes with out any interruption. Daemon threads run in the background and come into execution when the microprocessor is idle. The Garbage collection is good example for a daemon Thread. We can set a thread to be a daemon thread by calling method setDaemon (True) .

(i.e.) we can make a thread ‘t’ as deamon thread by using the method setDeamon()

Syntax for the Deamon Thread is as follows:

and to know whether the thread is deamon or not we can use the following syntax (i.e) isDeamon()


boolean x= t.isDeamon();

It returns true if the thread is a Deamon thread or it returns false if it is not a deamon thread depending upon the thread.

If the parameter is false thread is not a daemon thread. By default all threads are non daemon thread. A thread must be converted to a daemon thread explicitly that too before start() is calling in it. If set to daemon thread after the start() is called ,an exception Illegal thread state Exception is thrown by the JVM. Daemon thread is created by JVM.


We can't start the thread twice, it gives Illegal State Of Exception because already started thread cannot be called or start again.

Exexution flows between the two different threads

To explain the execution flow between the two different threads running simultaneous , above fig shows as:

  • First a main thread(i.e) main method which is invoking m1() at the same time whenever the main thread executed , the stacktrace is created for each and every flow.
  • m1() also sit in the stacktrace when it is executed and again m1() is invoking start(). In this state, the start() will have the separate thread to be started,which is shown in the fig.
  • start() internally invokes run() , again the run() will invoke write(). So all these flow is maintained in the stacktrace.
  • After the execution of write() it will pop from stacktrace to the run(). In the siilar way, after execution of start() , the control goes to main method.
  • In this way, the execution flow of thread follows.
  • An important thing is that, we cannot predict the result or execution flow in threads.

Thread Life Cycle:

thread life cycle
  • Whenever a new instance is created for thread then that is said to be the new state.
  • The threads which are in the runnable state are about to start because the CPU time is not held with those threads to get into the running state.
  • Threads will go to running state if the cup gives its time to those threads to execute.
  • When the thread work is finished or its run () has been finished its execution then the thread goes to END state.
  • If we want to pause the running thread for some time we must call yield () , which stops the thread for sometime in the thread pool. Here pausing the thread is different from going to the runnable state.
  • Once the thread is blocked it can’t come directly to runnable state.
  • So to go directly to runnable state, we have yield () to pause the thread, but where sleep() the thread will go to non-runnable state . It will be there until the time assigned to it in the sleep() method. For eg: t. sleep(1000);
  • When the thread t1 running with the appropriate logic, it is occurred with another thread which will run parallel but ‘t1’ thread wants to execute after the thread ‘t2’ because it is dependent on that thread. So the thread ‘t1’ will call join() method then the thread ‘t1’ will go to non-runnable state it will come back to runnable when the join() finishes it work.


Synchonization is nothing but when a thread is acting on one object then it prevents the acting of another thread to act on the same object.

  • Synchronization is a keyword.
  • When two or more Threads are participating in an application at a time one thread can access the particular critical block is called Synchronization.
  • It is a Non access modifier .
public synchronized boolean push(Object a) { --------- --------- Critical Block --------- }
  • Synchronized is used for only Methods/Blocks. We cannot use Synchronized for classes and fields.
  • In java every object has a lock including Arrays because Arrays are objects.
  • Thread contains multiple locks in one object.
  • If particular thread access a resources o f a object that object having a lock at a time only one thread can access.
  • Synchronized resources are access only that particular thread only another thread cannot access the resources.
  • A class is capable of having both synchronized and Non synchronized methods
  • If two Threads are execute synchronized method in a class and both threads are using same instance of the class to invoke the method at a time only one thread can execute. Another thread will need to wait until first one finishes.


Once a thread can acquire a lock on an object no other thread can enter any of the synchronized methods in that class.

example for thread memory allocation

In the above example in main memory x=4 stored this is the main copy after that t1 is created t1 calls in that thread x value 4 will be stored this is the local copy for that thread after that thread t2 can acquire a lock i.e., t1 is waiting for acquire a lock .The t2 thread will be displayed x value as 5 because in that thread we increase the value by 1 if this is completed i.e., t2 after that t1 acquire a lock i.e.,t1 will be executed.

wait ():

wait() should be called in synchronized block and it is called by the locked object

public void m() { synchronized (this) { x.wait(); } }

Here we get illegal state of exception because we use other object not current locked object. wait() method contains three more methods i.e.,

  • wait ();
  • wait (long milliseconds);
  • wait (seconds);

In wait () state we can call the notify() that goes to wait acquire a lock.

notify ():

It should be called in synchronized block and it is called by the locked object. When call notify() method than the notification is goes to one of thread in the waiting block and thread is invoked notify() that thread will release the lock.

notify () contains two more methods i.e.,

  • notify()
  • notifyAll()
HTML Comment Box is loading comments...