namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts...

34
Module - 4 Multi-Threaded Programming Terminologies Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is an independent path of execution within a single program. Multi-Threaded Programming: A process with two or more threads is being executed concurrently. Process based multi-tasking: It allows executing two or more processes concurrently. Example: Browsing the internet, editing PowerPoi t presentation concurrently. Thread based multi-tasking: It allows executing two or more threads concurrently. Example: Assume a program will be having 3 methods namely A(), B(), C(). Say thread T1, executes A(), thread T2 exe utes B(), Thread T3 executes C() concurrently. Difference between Process and Thread Process Thread Program under execution is called as Component or part of a program that can Proces s be executed independently is called as thread Each process has unique address space Threads shares same address space Inter Process communication is Inter thread communication is easier expensive and limited and inexpensive

Transcript of namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts...

Page 1: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Module - 4

Multi-Threaded Programming

Terminologies

Process: A program under execution is called as process.

Thread: A smallest component of a process that can be executed independently.

OR

A thread is an independent path of execution within a single program.

Multi-Threaded Programming: A process with two or more threads is being executed concurrently.

Process based multi-tasking: It allows executing two or more processesconcurrently. Example: Browsing the internet, editing PowerPoi t presentation concurrently.

Thread based multi-tasking: It allows executing two or more threadsconcurrently. Example: Assume a program will be having 3 methods namely A(), B(), C(). Say thread T1, executes A(), thread T2 exe utes B(), Thread T3 executes C() concurrently.

Difference between Process and Thread

Process Thread

Program under execution is called as Component or part of a program that canProcess be executed independently is called as

thread

Each process has unique address space Threads shares same address space

Inter Process communication is Inter thread communication is easierexpensive and limited and inexpensive

Processes are heavy Eight Threads are light weight

Java cannot handle process based multi- Java can handle thread based multi-Tasking tasking

Thread Priorities:o It is an integer number assigned to threads.o A priority indicates how one thread should be treated over other threads.

Page 2: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

o Thread priority is used to decide when to switch from one running thread to other.

o A method of switching from one running thread or process to other thread or process respectively is known as context switching.

When context switching happens

o A thread can voluntarily relinquish control i.e. running thread releases the CPU to run highest priority thread voluntarily or A thread can be pre-empted by a higher priority thread.

Main Threado When Java program starts execution, one thread begins immediately, that thread is

termed as main thread.o Main thread is required for two reasons, namely

This thread spawns child threads

Performs various shutdown activities before completing execution. o Main thread is a last thread to complete exe ution

Thread Life Cycle

There are five states a thread can possess in its life time, namely

1. New: Thread is in new state, when an instance of thread class is created and before calling start( ) method.

2. Runnable: A thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3. Running: The thread is in running state if the thread scheduler has selected it.4. Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently

not eligible to run.5. Terminated: A thread is in terminated or dead state when its run() method exits.

Page 3: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Thread Class

The Thread class contains following constructors and functions.

Constructors

Thread( )

Thread(String Name)

Thread(Runnable R)

Thread(Runnable R, String Name)

Functions Description

public void start( )Calls run( ) method to begin thread

execution

public void run( )Contains code that is to be executed by

thread

public void sleep( )Sends currently executing thread to

sleep mode

Page 4: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

public void sleep(long milliSecs) Sends currently executing thread tosleep mode for specified amount of time

public int getPriority( ) Returns priority of the Threadpublic void setPriority(int priority) Changes priority of current threadpublic String getName( ) Returns name of current thread

public Thread currentThread( )Returns reference of the currently

executing threadpublic int getId( ) Returns ID of the thread

Returns true, if thread is alivepublic boolean isAlive( ) Returns false, if thread has completed

Executionpublic void join( ) Waits for thread to die

public void join(long ms)Waits for thread to die for specified milli

Seconds

How to create Thread in Java?

There are two ways to create threads in Java, namely

1. By extending Thread class

2. By implementing Runnable interface

Creating Thread By extending Thre d cl ss

Follow below steps to create thread by ex ending Thread class,

1. Extend Sub class by Thread class

2. Override run( ) method of Thread class inside sub class

3. Create sub-class object

4. Call start( ) method by sub-class objectBelow program demonstrates the creation of thread.

/* ThreadDemo.java */

class thrExample extends Thread{

public void run(){

System.out.println("----Execution by Child Thread ----");

}

}

public class ThreadDemo {

public static void main(String [] args){

thrExample t1 = new thrExample();

thrExample t2 = new thrExample();

Page 5: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

t1.start();

t2.start();

}

}

Output:

---- Execution by Child Thread ----

---- Execution by Child Thread ----

Below program demonstrates various functions of Thread class. /* ThreadDemo.java */

class thrExample extends Thread{

thrExample(String thName){

super(thName);

}

public void run(){

System.out.println("---- New Thread ----");

System.out.println("Current Thre d : " +getName());

System.out.println("Thread Priority: " +getPriority());

System.out.println("Thread S at s : " +isAlive());

System.out.println("Thread Id : " +getId());

}

}

public class ThreadDemo {

public static void main(String [] args){ thrExample t1 = new thrExample("ONE"); thrExample t2 = new thrExample("TWO");System.out.println("Current Thread : "

+Thread.currentThread());

t1.start();

t2.start();

}

}

Output:

Current Thread : Thread[main,5,main] ---- New

Thread ----

Page 6: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Current Thread : TWO

Thread Priority: 5

Thread Status : true

Thread Id : 9

---- New Thread ----

Current Thread : ONE

Thread Priority: 5

Thread Status : true

Thread Id : 8

Creating Thread by Implementing Runnable Interface

Follow below steps to create thread by implementing Runnable I terface

1. Create sub class by implementing Runnable interface

2. Override run( ) method inside the subclass

3. Create Thread object by calling Thread constru tor and pass object of sub class as parameter for which Thread should be reated

4. Call start( ) method by Thread object

Below program demonstrates creation of thread by implementing Runnable interface.

/* ThreadRunn.java */

public class threadRun implements Runnable{ public void run()

{

System.out.println("Thread is executing using runnable interface");

}

public static void main(String[] args) { threadRun tr = new threadRun(); Thread t = new Thread(tr);

Thread t1 = new Thread(tr);

Thread t2 = new Thread(tr);

t.start();

t1.start();

t2.start();

}

Page 7: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

}

Output:

Thread is executing using runnable interface

Thread is executing using runnable interface

Thread is executing using runnable interface

How to create multiple threads

Below program demonstrates the creation of multiple threads

/* thExample.java */

class thExample implements Runnable{ Thread t;

thExample(String thName){

t = new Thread(this, thName);

System.out.println("New Thread ----" +t.getName() +"----is created");

t.start();

}

public void run(){

System.out.println("Thread --- " +t.getName() +" ---is executing");

}

}

public class threadRunMul {

public static void main(String [] args){ new thExample("ONE");

new thExample("TWO");

}

}

Output:

New Thread ----ONE---- is created

New Thread ----TWO---- is created

Thread --- TWO ---is executing

Thread --- ONE ---is executing

Page 8: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

isAlive( ) and join( )

1. Function belongs to : Thread class

Function Name: isAlive( )

Task: Checks whether the thread has finished execution

Prototype: final boolean isAlive( )

Return value: true, if thread upon which it is called is still running false, if thread upon which it is called is completed execution

2. Function belongs to : Thread class

Function Name: join( )

Task: waits until the thread on which it is called terminates

Prototype: final void join( ) or final void join(long milliSecs)

Return value: No return value

Below program demonstrates above two functions

class thRun implements Runnable{

Thread t;

thRun(String thName){

t = new Thread(this, thName);

t.start();

}

public void run(){

try{

for(int i = 1; i <= 2; i++){

System.out.println("Thread " +t.getName() +" "+i);

Thread.sleep(1000);

}

}catch(InterruptedException e){ System.out.println(t.getName() +" is Interrupted");

}

System.out.println(t.getName() +"is exiting");

}

}

public class thMulRun {

Page 9: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

public static void main(String [] args){ thRun t1 = new thRun("ONE");

thRun t2 = new thRun("TWO"); System.out.println("Main Thread Started"); System.out.println("Thread ONE is alive "

+t1.t.isAlive());

System.out.println("Thread ONE is alive "+t2.t.isAlive());

try{

System.out.println("Waiting for Child threads tofinish");

t1.t.join();

t2.t.join();

}catch(InterruptedException e){

System.out.println("Main thread Interrupted");

}

System.out.println("Main Thread Completed");

}

}

Output:

Main Thread Started

Thread ONE is alive true

Thread ONE is alive true

Waiting for child threads to finish

Thread TWO 1

Thread ONE 1

Thread TWO 2

Thread ONE 2

TWO is exiting

ONE is exiting

Main Thread Completed

Page 10: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Thread Priorities

Thread priorities are used by scheduler to decide when each thread should be allowed to run.

Functions Associated with Thread Priorities

1. Function belongs to : Thread class

Function Name: setPriority( )

Task: Changes priority of current thread

Prototype: public void setPriority( )

Return value: No return value

2. Function belongs to : Thread class

Function Name: getName( )

Task: Fetches the name of current thread on which it is called

Prototype: public String getName( )

Return value: Returns name of the thread

3. Function belongs to : Thread class

Function Name: setName( )

Task: Sets name to thread on which it is called

Prototype: public void setName(String Name)

Return value: No return value

4. Function belongs to : Thread class

Function Name: getId( )

Task: Fetches the Id of thread on which it is called

Prototype: public int getId( )

Return value: Returns integer number

Below program demonstrates various functions of Thread class. /* ThreadDemo.java */

class thrExample extends Thread{

thrExample(String thName){

super(thName);

}

public void run(){

System.out.println("---- New Thread ----");

System.out.println("Current Thread : " +getName());

Page 11: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

System.out.println("Thread Priority: " +getPriority());

System.out.println("Thread Status : " +isAlive());

System.out.println("Thread Id : " +getId());

}

}

public class ThreadDemo {

public static void main(String [] args){ thrExample t1 = new thrExample("ONE"); thrExample t2 = new thrExample("TWO");

System.out.println("Current Thread : "+Thread.currentThread());

t1.start();

t2.start();

}

}

Output:

Current Thread : Thread[main,5,main] ---- New Thread ---- Current Thread : TWO

Thread Priority: 5

Thread Status : true

Thread Id : 9

---- New Thread ----

Current Thread : ONE

Thread Priority: 5

Thread Status : true

Thread Id : 8

Page 12: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Synchronization

When two or more threads needs to access shared data, then data inconsistency problem arises. Imagine a scenario,

o Thread T1 is writing data into a file numbers.txt. o Thread T2 is reading data from a file numbers.txt.

In this scenario, when T1 is writing, if T2 reads the file concurrently, data may not be correct. Hence, when one thread is using shared resource, other threads should not be allowed to use until first thread completes the task.

In Java, synchronization is achieved using monitor or lock.

Each object has unique lock associated with them.

A thread that needs to access shared resource, first acquires the lock, as soon as completes the execution, thread automatically releases the lock.

To synchronize the function, prefix the keyword synchro zed in function definition

Example: In the below program, thread executes the fun tion “disp( )”, program without synchronization.

Synchronized Methods

/* ThreadSyncOne.java (Without Synchronization)*/class First{

void disp(){System.out.println("Good");try {

Thread.sleep(500);} catch (InterruptedException ex) { System.out.println("Thread Interrupted");}System.out.println("Morning");

}}class Two extends Thread{

First f = new First();Two(First f1){

f = f1;}public void run(){

f.disp();}

}

Page 13: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

public class ThreadSyncOne {public static void main(String [] args){ First f = new First();

Two t1 = new Two(f);Two t2 = new Two(f);t1.start();t2.start();

}}

Output:

Good

Good

Morning

Morning

Above Program using synchronized keyword

/* ThreadSyncOne.java (Using Synchroniz tion)*/class First{

void disp(){System.out.println("Good");try {

Thread.sleep(500);} catch (InterruptedException ex) { System.out.println("Thread Interrupted");}System.out.println("Morning");

}}class Two extends Thread{

First f = new First();Two(First f1){

f = f1;}public void run(){

f.disp();}

}public class ThreadSyncOne {

Page 14: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

public static void main(String [] args){ First f = new First();

Two t1 = new Two(f);Two t2 = new Two(f);t1.start();t2.start();

}}

Output:

Good

Morning

Good

Morning

Synchronized Blocks

Synchronized blocks are required when,o Synchronize access to objects of a class that was not designed for multi-threading.o Class does not use synchronized methods.

During above conditions, synchronized blocks can be used. synchronized(Object){

//Statements to be synchronized}Where, Object is a reference to the object being referenced.

Below, program demonstrates the use of synchronized block. /* ThreadSyncBlock.java*/

class Callme{void disp(){

System.out.println("Good");try {

Thread.sleep(500);} catch (InterruptedException ex) { System.out.println("Thread Interrupted");}System.out.println("Morning");

}}

class Caller implements Runnable{ Callme c;

Thread t;

Page 15: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

public Caller(Callme thrObj){c = thrObj;t = new Thread(this);t.start();

}

public void run(){synchronized(c){

c.disp();}

}}public class ThreadSyncBlock {

public static void main(String [] args){ Callme cmObj = new Callme(); Caller c1 = new Caller(cmObj); Caller c2 = new Caller(cmObj);}

}

Output:

Good

Morning

Good

Morning

Inter Thread Communication

It is mechanism that allows two or more synchronized threads to communicate with each other.

In Java, Inter thread communication is achieved using

o wait( ) o notify( )o notifyAll( )

wait( )

The wait method releases the lock of current thread and moves it to waiting state. Thread will awake, when other thread calls notify( ) or notifyAll( ) method for the object, or till specified time elapses.

Prototype:

1. public final void wait( ) throws InterruptedException

2. public final void wait(long timeout) throws InterruptedException

Page 16: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

notify( )

Notifies the thread in waiting state on the same object to wake up.

Prototype:

1. public final void notify( )

notifyAll( )

Notifies all threads in waiting state on the same object to wake up.

Prototype:

1. public final void notifyAll( )

Process of Inter Thread Communication

Working of Threads with respect to abo e diagram

1. Threads enter to acquire lock.

2. Lock is acquired by on thread.

3. Now thread goes to aiting state if you call wait() method on the object.Otherwise it releases the lock and exits.

4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).

5. Now thread is available to acquire lock.

6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Page 17: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Difference between wait( ) and sleep( )

wait( ) sleep( )

wait( ) method releases the locksleep( ) method does not releases the

lockMethod of object class Method of Thread classNon-static method Static methodShould be notified by notify( ) or wakes up after specified timenotifyAll( )

Below program demonstrates the withdrawal and depositing money using inter thread communication.

Scenario:

Available balance in the account is 5000.

Say, Thread T1, tries to withdraw an amount of 10000. S ce, balance is less, thread cannot withdraw. It calls wait( ) and goes to waiting state until another thread deposits money and wakes up this thread

Say, Thread T2, deposits 10000, now balance is 15000. Now, T2 calls notify( ) method and wakes up thread T1.

Now, T1 resumes with its execution.

/* threadWaitNotify */class Customer{

int amount = 5000;

synchronized void withdraw(int withAmount){ System.out.println("About to withdraw");

if(amount < ithAmount){ System.out.println("No Sufficient Funds"); Try{

ait();}catch(Exception e){

System.out.println("Waiting to deposit, but done");}

Page 18: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

amount = amount - withAmount;System.out.println("Withdrawl of " +withAmount +"completed");

}}synchronized void deposit(int depAmount){System.out.println("Depositing Amount"); amount = amount + depAmount; System.out.println("Depositing " +depAmount); notify();

}}

public class ThreadWaitNotify {public static void main(String [] args){ final Customer c = new Customer(); new Thread(){

public void run(){

c.withdraw(10000);}

}.start();new Thread(){

public void run(){c.deposit(10000);

}}.start();

}}Producer – Consumer Problem

In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.

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

At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a time.

Page 19: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

Problem

To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to remove data from an empty buffer.

Solution

The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer.

An inadequate solution could result in a deadlock where both processes are waiting to be awakened.Below program demonstrates the Producer – Consumer problem using Linked List.

/* ThreadExample */import java.util.LinkedList;

public class Threadexample{

public static void main(String[] args)throws InterruptedException

{/ Object of a class that has both produce()/ and consume() methodsfinal PC pc = new PC();

// Create producer threadThread t1 = new Thread(new Runnable(){

@Overridepublic void run(){

try{

pc.produce();}catch(Interrup edException e){

e.printStackTrace();}

}});

// Create consumer threadThread t2 = new Thread(new Runnable(){

Page 20: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

@Overridepublic void run(){

try{

pc.consume();}catch(InterruptedException e){

e.printStackTrace();}

}});/ Start both threadst1.start();t2.start();

/ t1 finishes before t2t1.join();t2.join();

}

/ This class has a list, producer (adds items to list/ and consumber (removes items).public static class PC{

/ Create a list shared by producer and consumer/ Size of list is 2.LinkedList<Integer> list = new LinkedL st<>(); int capacity = 2;

// Function called by producer threadpublic void produce() throws InterruptedException{

int value = 0;while (true){

synchronized ( his){

/ producer thread waits while list/ is fullwhile (list.size()==capacity)

ait();

System.out.println("Producer produced-" + value);

Page 21: namrathakalasannavar955210856.files.wordpress.com.…  · Web viewWhen Java program starts execution, one thread begins immediately, that thread is termed as main thread. Main thread

/ to insert the jobs in the list list.add(value++);

/ notifies the consumer thread that/ now it can start consuming notify();

/ makes the working of program easier/ to understandThread.sleep(1000);

}}

}// Function called by consumer threadpublic void consume() throws InterruptedException{

while (true){

synchronized (this){

/ consumer thread waits while list/ is emptywhile (list.size()==0)

wait();

//to retrive the ifrst job in the list int val = list.removeFirst();

System.out.println("Consumer co sumed-" + val);

/ Wake up producer thread notify();

/ and sleep Thread.sleep(1000);

}}

}}

}Output:Producer produced-0Producer produced-1Consumer consumed-0Consumer consumed-1Producer produced-2Consumer consumed-2