Home » Posts tagged 'thread'

Tag Archives: thread

Thread Life Cycle in Java

Life cycle of Thread tells the various information of thread form born to terminate. Thread life cycle contains the several stages and at a time any thread can be present  in a single state.

States of Thread life cycle

  1. Born
  2. Ready
  3. Running
  4. Blocked
  5. Sleep
  6. Wait
  7. Dead
Java Thread Life Cycle
Java Thread Life Cycle

Ready:  In this state thread is ready to execute but not running. 

When the start() method calls thread enters from born to ready state.

Running:  When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.

Thread can visit more than ones in a running state.

Blocked: When a running thread has a input-output issue it enters in a blocked state from running state and when input-output issue solves it again comes in a running thread.

Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.

When sleep time expires then thread moves to ready state.

Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.

When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.

Dead: A running thread is enter in a dead state when its execution completes (run() method completes)   or terminate for any reason.

Thread isAlive() and join() Methods in Java

There are two ways  to determine whether a thread has finished or not.

  •   isAlive()
  •   join()

isAlive():  isAlive() method is used to check whether a thread is in the running or not .


In a another word, this method determines thread is live or dead. 

isAlive( )method returns true if the thread is still running otherwise  it returns false.

join(): This method wait for the specified thread to terminate.


Thread suspend() and resume() method in Java

suspend() : This method suspend a thread for sometime but do not kill/terminate it.

resume() : This method revives the suspended thread.

Thread stop method in Java

In java, stop()  method  kills/terminates  the currently executing thread.


Description: in the above program, when value of variable i=3 then stop() method terminates the curently executing thread and come out of the loop.

Thread Yield method in Java

In java, yield()  method  temporarily pause  the currently executing thread object  and allow other threads to execute.

Producer Consumer Problem in Java

In computing, producer–consumer problem also known as the bounded-buffer problem.

In the producer–consumer problem there are two processes, first is producer and the second is consumer, who share a common, fixed-size buffer.

 The producer’s job is to generate data, put it into the buffer and start again.

At the same time, the consumer’s job is consuming the data, one piece at a time and removing it from the buffer.

The producer–consumer problem occurs when the producer try to add data into the buffer if it’s full and the  same consumer  try to remove data from an empty buffer.

Solution of Producer & Consumer

The solution for the producer must go to sleep if the buffer is full and the consumer must consume data. 

Once the data is consumed it removes from the buffer by consumer process. Consumer process  also notifies the producer, to  starts fill the buffer again.

Similarly, the consumer process must go to sleep if it finds the buffer is empty and the producer puts data into the buffer.

Ones the data is filled into buffer by producer process it also notifies the Consumer, to  starts consume the data from buffer.

Description : In the above program there are four classes: Item, Producer, Consumer and  PCDemo

Item: the class is trying to synchronize.  

Producer: produces the data.   

Consumer: consumes the data produced by producer class.      

PCDemo: a class that creats the class Item, Producer and Consumer.

In the above program we can see that, producer process producess the data and  consumed by consuner process, then again a producer process producess a new data and consumed by consumer process and so on.                       

To stop the execution we have to pess ”Ctrl+C”.

Thread Synchronization in Java

When two or more threads try to access the same resource, they need somehow to ensure that the resource will be used by only one thread at a time.

The process by which this achive is called Synchronization. Java uses the concept of monitor (also called semaphore) for Synchronization.

The monitor allows one thread at a time to execute a Synchronized method. Only one thread at a time may hold a lock on a monitor.

For a thread can lock or unlock each object in Java is associated with a monitor.

Example: Write a program to synchronize a thread.

In the above program, nothing exist to stop all three threads from entering write () method while other thread is using it.

These three threads are racing each other to complete the method and this condition is known as a race condition.

To fix this program, we must serialize access to write () method and restrict its access to only one thread at a time.

To do this, we simply need to write synchronized keyword before write () method definition. It is known as a synchronized method.

Synchronized Method

above method write() can be changed as below

Synchronized block: this technique is also used for thread synchronization

using synchronization block we can change write method as below

This prevent other threads from entering in write () method while other thread is using it. After synchronized has been added to write (), the output of the program.


Thread Priorities in Java

In java, when two or more than  two thread is computing for CPU time, every thread is assigned a priority value. A highest Priority thread get preference over lower priority thread.  

All Java threads have a priority in the range 1-10.

Top priority is 10, lowest priority is 1.Normal priority ie. priority by default is 5.

Thread.MIN_PRIORITY –      1      minimum thread priority

Thread.MAX_PRIORITY –     10    maximum thread priority

Thread.NORM_PRIORITY –  5      maximum thread priority

Whenever a new Java thread is created it has the same priority as the thread which created it.

Thread priority can be changed by the setPriority() method.

Example: Write a program to demonstrate the thread priority.

Thread Creation in Java

We can create a thread by two ways:

  1. By implementing Runnable interface
  2. By extending Thread

By Implementing Runnable Interface

  1. We can create a thread by creating a class that implements the Runnable interface.
  2. To implement Runnable, a class only need to implement a single method called run().
  3. Inside run () we will define the code that constitute the new thread.    
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.  


Passing “this” as a argument, “DemoThread” is the name of the thread.  

In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.

This cause the child thread terminates earlier than main thread.

By Extending Thread

  1. To create a thread we will create a thread a class that extends Thread class.
  2. To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
  3. Inside run () we will define the code that constitute the new thread.                                                                                 
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.

Main Thread in Java

In Java programming, when a program begins the first thread that starts running is called main thread.

 Other threads(child thread) can be spawned from this main thread.

When program terminates, the main thread must be the last thread in the program to end. When the main thread stops, the program stops running.

Main thread is created automatically, but it can be controlled by the program by using a Thread object.

By default name of main thread is “main”

By default Group name of main thread is “main”

By default priority of main thread is “5”.

Q.1 WAP to print the main thread and change the name of the main thread.


Q.2 WAP to print the 1 to 5 using thread and illustrate the use of sleep().


Managed by MochaHost - Fast & Easy WordPress Hosting