0% found this document useful (0 votes)
92 views15 pages

Unit - 4: Multithreading

This document discusses multithreading in Java. It defines multithreading as allowing parts of a program to run concurrently by sharing processing resources. The advantages include not blocking the user and saving time by performing operations together. It describes the Java thread model including single-threaded and multithreaded systems. It also discusses thread states like new, runnable, running, dead, and blocked. Finally, it covers creating threads by extending the Thread class or implementing the Runnable interface.

Uploaded by

Gouthami Nara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views15 pages

Unit - 4: Multithreading

This document discusses multithreading in Java. It defines multithreading as allowing parts of a program to run concurrently by sharing processing resources. The advantages include not blocking the user and saving time by performing operations together. It describes the Java thread model including single-threaded and multithreaded systems. It also discusses thread states like new, runnable, running, dead, and blocked. Finally, it covers creating threads by extending the Thread class or implementing the Runnable interface.

Uploaded by

Gouthami Nara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Object Oriented Programming Through Java

UNIT – 4
Multithreading
Multithreading: The Java thread model, Creating threads, Thread priorities,
Synchronizing threads, Interthread communication.

INTRODUCTION

Java is a multi-threaded programming language which means we can develop multi-threaded


program using Java. A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same time making optimal use of
the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Advantages of Java Multithreading:


1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.

Differences between Multithreading and Multitasking


Multithreading Multitasking
It is a programming concept in which a It is operating system concept in which
program or a process is divided into two or multiple tasks are performed simultaneously.
more subprograms or threads that are
executed at the same time in parallel.
It supports execution of multiple parts of a It supports execution execution of multiple
single program simultaneously. programs simultaneously.
The processor has to switch between The processor has to switch between
different parts or threads of a program. different programs or processes.
It is highly efficient. It is less efficient in comparison to
multithreading.

Prepared by Priyanka Pulagouni 1


Object Oriented Programming Through Java

A thread is the smallest unit in A program or process is the smallest unit in a


multithreading. multitasking environment.
It helps in developing efficient programs. It helps in developing efficient operating
systems.
It is cost-effective in case of context It is expensive in case of context switching.
switching.

JAVA THREAD MODEL

 The Java run-time system depends on threads for many things, and all the class
libraries are designed with multithreading.
 In fact, Java uses threads to enable the entire environment to be asynchronous. This
helps reduce inefficiency by preventing the waste of CPU cycles.
 Java thread models are
o Single thread system
o Multithread system
Single thread System
 Single-threaded systems use an approach called an event loop with polling.
 In this model, a single thread of control runs in an infinite loop, polling a single event
queue to decide what to do next.
 Once this polling mechanism returns with, say, a signal that a network file is ready to
be read, then the event loop dispatches control to the appropriate event handler.
 Until this event handler returns, nothing else can happen in the system. This wastes
CPU time.
 It can also result in one part of a program dominating the system and preventing any
other events from being processed.
 In general, in a singled-threaded environment, when a thread blocks (that is, suspends
execution) because it is waiting for some resource, the entire program stops running.

Multithread system
 The benefit of Java’s multithreading is that the main loop/polling mechanism is
eliminated.
 One thread can pause without stopping other parts of program.
 For example, the idle time created when a thread reads data from a network or waits
for user input can be utilized elsewhere.
 Multithreading allows animation loops to sleep for a second between each frame
without causing the whole system to pause.
 When a thread blocks in a Java program, only the single thread that is blocked pauses.
All other threads continue to run.

Prepared by Priyanka Pulagouni 2


Object Oriented Programming Through Java

LIFE CYCLE OF A THREAD

A thread is always in one of five states:


1. New-born state
2. Runnable state
3. Running state
4. Dead state
5. Blocked state
The below figure shows the life-cycle of a thread.

The newborn state


When a thread is called, it is in the new-born state, that is, when it has been created
and is not yet running. In other words, a start () method has not been invoked on this thread.
In this state, system resources are not yet allocated to the thread. When a thread is in the
newborn state, calling any method other than start () method causes an
IllegalThreadStateException.

The runnable state


A thread in the runnable state is ready for execution but is not being executed
currently. Once a thread is in the runnable state, it gets all the resources of the system (as, for
example, access to the CPU) and moves on to the running state.

All runnable threads are in a queue and wait for CPU access. When the start () method is
called on the newborn thread, it will be in the runnable state. It is not in the running state yet
because system resources such as the CPU (which might be serving another thread at that
point) are not available.

Prepared by Priyanka Pulagouni 3


Object Oriented Programming Through Java

The running state


After the runnable state, if the thread gets CPU access, it moves into the running state.
The thread will be in the running state unless one of the following things occur:
• It dies (that is, the run () method exits).
• It gets blocked to the input/output for some reason.
• It calls sleep ().
• It calls wait ().
• It calls yield ().
• It is preempted by a thread of higher priority.
• Its quantum (time slice) expires.
A thread with a higher priority than the running thread can preempt the running thread
if any of the following situations arise:
• If the thread with the higher priority comes out of the sleeping state.
• The I/O completes for a thread with a higher priority waiting for that I/O.
• Either notify () or notifyAll () is called on a thread that called wait.
When a thread calls the wait () method it goes in the waiting state. To wake up this thread,
some other running thread should notify it.

The dead state


A thread goes into the dead state in two ways:
• If its run () method exits.
• A stop () method is invoked.
The run () method exits when it finished execution naturally or throws an uncaught
exception. The stop () method kills the thread. A thread in the dead state cannot be executed
further.

The blocked state


A thread can enter the blocked state when one of the following five conditions occurs:
• When sleep () is called,
• When suspend () is called,
• When wait () is called,
• The thread calls an operation, (For example, during input/output, a thread will not return
until the I/O operation completes.),
• The thread is waiting for monitor.
A thread in the blocked state waits for some action to happen so that it can get ready.
That is, if the thread requires some of the I/O operation, it will enter into the blocked state by
giving the access to the CPU to another thread. After completion of the I/O operations it will
enter into the runnable state.
A thread must move out of a blocked state into the runnable (or running) state using
the opposite of whatever phenomenon put it into the blocked state.
• If a thread has been put to sleep (), the specified timeout period must expire.
• If a thread has called wait (), then some other thread using the resource for which the first
thread is waiting must call notify () or notifyAll ().

Prepared by Priyanka Pulagouni 4


Object Oriented Programming Through Java

• If a thread is waiting for the completion of an input or output operation, then the operation
must finish.

CREATING THREADS

In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.
1. Using Thread class (by extending Thread class)
2. Using Runnable interface (by implementing Runnable interface)

Extending Thread class

The java contains a built-in class Thread inside the java.lang package. The Thread class
contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.

Example
class SampleThread extends Thread{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();

Prepared by Priyanka Pulagouni 5


Object Oriented Programming Through Java

}
}

Implementng Runnable interface

The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter
to the Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.

Example

class SampleThread implements Runnable{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}

The Thread class in java is a subclass of Object class and it implements Runnable interface.
The Thread class is available inside the java.lang package. The Thread class has the
following syntax.

Prepared by Priyanka Pulagouni 6


Object Oriented Programming Through Java

class Thread extends Object implements Runnable{


...
}

The Thread class has the following consructors.


o Thread( )
o Thread( String threadName )
o Thread( Runnable objectName )
o Thread( Runnable objectName, String threadName )
The Thread classs contains the following methods.

Method Description Return Value

run( ) Defines actual task of the thread. void

start( ) It moves there thread from Ready state to Running void


state by calling run( ) method.

setName(String) Assigns a name to the thread. void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

currentThread( ) Returns the reference of the thread that currently in void


running state.

sleep( long ) moves the thread to blocked state till the specified void
number of milliseconds.

isAlive( ) Tests if the thread is alive. boolean

yield( ) Tells to the scheduler that the current thread is void


willing to yield its current use of a processor.

join( ) Waits for the thread to end. void

Prepared by Priyanka Pulagouni 7


Object Oriented Programming Through Java

THREAD PRIORITIES

Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others.
Thread priorities are integers that specify the relative priority of one thread to another.
As an absolute value, a priority is meaningless; a higher-priority thread doesn’t run
any faster than a lower-priority thread if it is the only thread running.
Instead, a thread’s priority is used to decide when to switch from one running thread
to the next. This is called a context switch.
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads.
However, thread priorities cannot guarantee the order in which threads execute and
are very much platform dependent.
The rules that determine when a context switch takes place are simple:
o A thread can voluntarily relinquish control. This is done by explicitly yielding,
sleeping, or blocking on pending I/O. In this scenario, all other threads are
examined, and the highest-priority thread that is ready to run is given the CPU.
o A thread can be preempted by a higher-priority thread. In this case, a lower-
priority thread that does not yield the processor is simply preempted—no
matter what it is doing— by a higher-priority thread. Basically, as soon as a
higher-priority thread wants to run, it does. This is called preemptive
multitasking.
In cases where two threads with the same priority are competing for CPU cycles, the
situation is a bit complicated.
o For windows - round-robin fashion,
o For other types of operating systems, threads of equal priority must voluntarily
yield control to their peers

Daemon Thread

 Daemon thread is the low priority thread which runs in the background to perform
garbage collection.
 It always depends on user threads.
 JVM does not have control over daemon thread. It can keep running even when the
program has stopped.

Prepared by Priyanka Pulagouni 8


Object Oriented Programming Through Java

Example: Program to create a daemon thread in Java


public class ThreadDemo extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon Thread");
}
else
{
System.out.println("User Thread");
}
}
public static void main(String[] args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}

Output:
Daemon Thread
User Thread
User Thread

SYNCHRONIZATION

The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.
In java, the synchronization is achieved using the following concepts.
1. Mutual Exclusion
2. Inter thread communication

Prepared by Priyanka Pulagouni 9


Object Oriented Programming Through Java

Mutual Exclusion

Using the mutual exclusion process, we keep threads from interfering with one
another while they accessing the shared resource. In java, mutual exclusion is achieved using
the following concepts.
 Synchronized method
 Synchronized block

Synchronized method

When a method created using a synchronized keyword, it allows only one object to access it
at a time. When an object calls a synchronized method, it put a lock on that method so that
other objects or thread that are trying to call the same method must wait, until the lock is
released. Once the lock is released on the shared resource, one of the threads among the
waiting threads will be allocated to the shared resource.

In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.

Prepared by Priyanka Pulagouni 10


Object Oriented Programming Through Java

Example

class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
class MyThread_1 extends Thread{
Table table = new Table();
int number;
MyThread_1(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
class MyThread_2 extends Thread{
Table table = new Table();
int number;
MyThread_2(Table table, int number){
this.table = table;
this.number = number;
}
public void run() {
table.printTable(number);
}
}
public class ThreadSynchronizationExample {

public static void main(String[] args) {


Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}

Prepared by Priyanka Pulagouni 11


Object Oriented Programming Through Java

Synchronized block

The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method. For example, let's consider a method with 20 lines of code where we want
to synchronize only a sequence of 5 lines code, we use the synchronized block.

The folllowing syntax is used to define a synchronized block.

Syntax
synchronized(object)
{
...
block code
...
}

Example

import java.util.*;

class NameList {
String name = "";
public int count = 0;

public void addName(String name, List<String> namesList){


synchronized(this){
this.name = name;
count++;
}
namesList.add(name);
}

public int getCount(){


return count;
}
}
public class SynchronizedBlockExample {
public static void main (String[] args)
{
NameList namesList_1 = new NameList();
NameList namesList_2 = new NameList();
List<String> list = new ArrayList<String>();
namesList_1.addName("Rama", list);

Prepared by Priyanka Pulagouni 12


Object Oriented Programming Through Java

namesList_2.addName("Seetha", list);
System.out.println("Thread1: " + namesList_1.name + ", " + namesList_1.getCount() +
"\n");
System.out.println("Thread2: " + namesList_2.name + ", " + namesList_2.getCount() +
"\n");
}
}

INTERTHREAD COMMUNICATION

Inter thread communication is the concept where two or more threads communicate to solve
the problem of polling. In java, polling is the situation to check some condition repeatedly, to
take appropriate action, once the condition is true. That means, in inter-thread
communication, a thread waits until a condition becomes true such that other threads can
execute its task. The inter-thread communication allows the synchronized threads to
communicate with each other.

Java provides the following methods to achieve inter thread communication.

 wait( )
 notify( )
 notifyAll( )

The following table gives detailed description about the above methods.

Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

Let's look at an example problem of producer and consumer. The producer produces the item
and the consumer consumes the same. But here, the consumer cannot consume until the
producer produces the item, and producer cannot produce until the consumer consumes the
item that already been produced. So here, the consumer has to wait until the producer
produces the item, and the producer also needs to wait until the consumer consumes the
same. Here we use the inter-thread communication to implement the producer and consumer
problem.

Prepared by Priyanka Pulagouni 13


Object Oriented Programming Through Java

The sample implementation of producer and consumer problem is as follows.

Example
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}

Prepared by Priyanka Pulagouni 14


Object Oriented Programming Through Java

notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}

class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);

}
}

Prepared by Priyanka Pulagouni 15

You might also like