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.

Please follow and like us:
error

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 .

                                                or

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.

Result

Please follow and like us:
error

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.

Please follow and like us:
error

Thread stop method in Java

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

Result

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.

Please follow and like us:
error

Thread Yield method in Java

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

Please follow and like us:
error

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”.

Please follow and like us:
error

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.

Output:     

Please follow and like us:
error

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.

Please follow and like us:
error

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.

Output:

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

Output:

Please follow and like us:
error

Multithreading in Java

A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

Difference between Process and Thread

Process Thread
A process has their own virtual address space. Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space. Two threads running within a process uses the same address space.
Every process has its own data segment All threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes. In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead. Threads have almost no overhead;
Process is heavy weight. Threads are light weight process (LWP).
Process contains much information about system, resource. Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process. No duplication of resources is required when we create a child thread from main thread.

Thread Creation in Java

We can create a thread by two ways:

  1. By extending Thread
  2. By implementing Runnable interface

Lets see multithreading in java with example

Creating 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.  

Result

Description:

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.

Creating Thread By Extending Thread Class

  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.

Result

Thread Methods in Java

Commonly used methods of Thread class are as follows

Sr No Method and Description
1 void run()
Work execute as a thread is defined in this method .
2 void start()
Used to start a thred which Calls the run() method of the thread or child class.
3 static void sleep(long miliseconds)
Suspend the thread for specified amount of time.
4 static void sleep(long miliseconds,int nanos)
Suspend the thread for specified amount of time.
5 void join()
This method is used to pause the ececution of current thread until it die. void join().
6 void join(long miliseconds)
Pause the execution of current thread for the pecified miliseconds.
7 void join(long miliseconds,int nanos)
Pause the execution of current thread for the pecified miliseconds and nano seconds.
8 boolean isAlive()
To checks a thread is alive or not.
9 String getName()
Returns the name of the thread.
10 setName(String name)
Used to set the name of thread.
11 int getPriority()
Get the priority of the thread.
12 void setPriority(int priority)
Set the priority of thread.
13 static Thread currentThread()
Returns the reference of currently executing thread
14 long getId()
Returns the id of the thread.
15 static void yield()
Temporarily pause the currently executing thread and allow other threads to execute.
16 void suspend()
Used to suspend the thread.
17 void resume()
Used to resume the suspended thread.
18 void stop()
Used to stop the thread.
19 void interrupt()
Interrupts the thread.
20 boolead isInterrupted()
Check whether the thead is interrupted or not
Please follow and like us:
error