0% found this document useful (0 votes)
6 views

Unit III Multi Threading Notes

The document provides an overview of multithreading in Java, explaining its definition, advantages, and the differences between multitasking and multithreading. It details the lifecycle of a thread, methods for creating threads, thread priorities, synchronization, and inter-thread communication. Additionally, it discusses thread management techniques such as suspending, blocking, and stopping threads.

Uploaded by

23eg112a52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit III Multi Threading Notes

The document provides an overview of multithreading in Java, explaining its definition, advantages, and the differences between multitasking and multithreading. It details the lifecycle of a thread, methods for creating threads, thread priorities, synchronization, and inter-thread communication. Additionally, it discusses thread management techniques such as suspending, blocking, and stopping threads.

Uploaded by

23eg112a52
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit III- Multithreading in JAVA

Q1. What is Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process. Java
Multithreading is mostly used in games, animation, etc.

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.
--------------------------------------------------------------------------------------------------------------------
Q2. What is Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:

1. Process-based Multitasking (Multiprocessing)

2. Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

Each process has an address in memory. In other words, each process allocates a
separate memory area. A process is heavyweight. Cost of communication between the
process is high.
Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

Threads share the same address space. A thread is lightweight. Cost of communication
between the thread is low.
Unit III- Multithreading in JAVA

Process-Based Multitasking Thread-Based Multitasking


This deals with "Big Picture" This deals with Details
These are Heavyweight tasks These are Lightweight tasks
Inter-process communication is expensive
and Inter-Thread communication is inexpensive.
limited
Context switching from one process to Context switching is low cost in terms of
another is memory,
because they run on the same address
costly in terms of memory space
This is not under the control of Java This is controlled by Java

---------------------------------------------------------------------------------------------------------------------
Q3. Define a Thread

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate


path of execution. Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
Unit III- Multithreading in JAVA

Note: At a time one thread is executed only.

Thread class

Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface

---------------------------------------------------------------------------------------------------------------------

Q4. With a neat sketch explain Life cycle of a Thread (Thread States)

A thread can be in one of the five states. In general terms, a thread can running. It can
be ready to run as soon as it gets the CPU time. A running thread can be suspended,
which is a temporary halt to its execution. It can later be resumed. A thread can be
blocked when waiting for the resource. A thread can be terminated.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Blocked/Terminated
5. Destroy
Unit III- Multithreading in JAVA

Newborn State: When we create a thread, it is said to be in the new born state. At
this state we can do the following:

• schedule it for running using the start () method.


• Kill it using stop () method.

Runnable State: A runnable state means that a thread is ready for execution and
waiting for the availability of the processor. That is the thread has joined the queue of
the threads for execution. If all the threads have equal priority, then they are given
time slots for execution in the round robin fashion, first-come, first-serve manner. The
thread that relinquishes the control will join the queue at the end and again waits for
its turn. This is known as time slicing. Running State:
Unit III- Multithreading in JAVA

Running state: Running state means that the processor has given its time to the
thread for it execution. The thread runs until it relinquishes the control or it is pre-
empted by the other higher priority thread. As shown in the fig. a running thread can
be preempted using the suspend(), or wait(), or sleep() methods.

Blocked state: A thread is said to be in the blocked state when it is prevented from
entering into runnable state and subsequently the running state.

Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed execution. It is a natural death. However we also can kill the thread by
sending the stop () message to it at any time.

The Thread Methods:

Sl No Method Name Description


1 run() Used to write the body of the thread
2 start() Used to start the thread
3 sleep() Used to make the thread sleep for milliseconds
4 suspend() Used to suspend a running thread
5 wait() Waits until further ordered
Used to give control to other thread before it turn
6 yield comes
7 Stop() Used to stop the thread
8 resume() Used to start the blocked thread
9 notify() Used to notify the waiting thread
10 notifyAll() Used to notify theall waiting threads

-------------------------------------------------------------------------------------------------------------------
Q5. How can a thread be created? Or what are the two ways of creating a thread

There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

Thread class:
Unit III- Multithreading in JAVA

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

1. Thread ()
2. Thread (String name)
Thread (Runnable r)
3. Thread (Runnable r,String name)

Commonly used methods of Thread class:

public void run (): is used to perform action for a thread.

public void start (): starts the execution of the thread. JVM calls the run()

Runnable interface:

The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().

1) Java Thread Example by extending Thread class

class Multi extends Thread


{
public void run()
{

System.out.println("thread is running...");

}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}

Output:thread is running...
Unit III- Multithreading in JAVA

2) Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Output:thread is running

Q6. The Thread Priorities

Thread priorities are used by the thread scheduler to decide when and which thread
should be allowed to run. In theory, higher-priority threads get more CPU time than
lower-priority threads.
In practice, the amount of CPU time that a thread gets often depends on several
factors besides its priority. (For example, how an operating system implements
multitasking can affect the relative availability of CPU time.) A higher-priority thread can
also preempt a lower-priority one. For instance, when a lower-priority thread is running
and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it
will preempt the lower priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:

final void setPriority(int level)


Unit III- Multithreading in JAVA

Here, level specifies the new priority setting for the calling thread. The value of level
must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined as static final
variables within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:

final int getPriority()


import java. io.*;
class PThread1 extends Thread
{
public void run()

{
System. out. println(" Child 1 is started");
}

}
class PThread2 extends Thread

{
public void run()

{
System. out. println(" Child 2 is started");
}

}
class PThread3 extends Thread

{
public void run ()

{
System. out. println(" Child 3 is started");
}

class PTest
Unit III- Multithreading in JAVA

{
public static void main (String args[])
{

//setting the priorities to the thread using the setPriority () method

PThread1 pt1=new PThread1();


pt1.setPriority(1);

PThread2 pt2=new PThread2();


pt2.setPriority(9);

PThread3 pt3=new PThread3();


pt3.setPriority(6);

pt1.start();
pt2.start();
pt3.start();

//getting the priority


System. out. println ("The pt1 thread priority is :"+pt1.getPriority());
}

-----------------------------------------------------------------------------------------------------------------------
Q7. Thread Synchronization in Java with an example

When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization.

Key to synchronization is the concept of the monitor (also called a semaphore). A monitor
is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a
monitor at a given time. When a thread acquires a lock, it is said to have entered the
monitor. All other threads attempting to enter the locked monitor will be suspended until the
first thread exits the monitor. These other threads are said to be waiting for the monitor. A
thread that owns a monitor can reenter the same monitor if it so desires.
Unit III- Multithreading in JAVA

Example without the synchronization:

class Bank
{
int bal;
public Bank()
{
bal=5000;
}
public void withdraw(int bal1)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
bal=bal-bal1;
System.out.println("Balance is ="+bal);
}
}
Class ConBank implements Runnable
{
Bank b;
public ConBank(Bank b1)
{
b=b1;
}
public void run()
{
b.withdraw(500);
}
}
class MainBank
{
public static void main(String args[])
{
Bank o1= new Bank();
ConBank c1= new ConBank(o1);
Thread t1=new Thread(c1);
Thread t2= new Thread(c1);
t1.start();
t2.start();
}
}
Unit III- Multithreading in JAVA

Output
Balance is:4000
Balance is:4000

Using the Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.


Synchronized method is used to lock an object for any shared resource. When a thread
invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

The general form of the synchronized method is:

synchronized type method_name(para_list)

//body of the method

where synchronized is the keyword, method contains the type, and method_name
represents the name of the method, and para_list indicate the list of the parameters.

Example using the synchronized method

class Bank
{
int bal;
public Bank()
{
bal=5000;
}
public synchronized void withdraw(int bal1)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
bal=bal-bal1;
System.out.println("Balance is ="+bal);
}
Unit III- Multithreading in JAVA

}
Class ConBank implements Runnable
{
Bank b;
public ConBank(Bank b1)
{
b=b1;
}
public void run()
{
b.withdraw(500);
}
}
class MainBank
{
public static void main(String args[])
{
Bank o1= new Bank();
ConBank c1= new ConBank(o1);
Thread t1=new Thread(c1);
Thread t2= new Thread(c1);
t1.start();
t2.start();
}
}

Output
Balance is:4500
Balance is:4000
---------------------------------------------------------------------------------------------------------------------

Q8. Inter-Thread Communication


If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate
indirectly. Through, synchronized method, each thread always competes for the
resource. This way of competing is called polling. The polling wastes the much of the
CPU valuable time. The better solution to this problem is, just notify other threads for the
resource, when the current thread has finished its task. This is explicit communication
between the threads.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods.
These methods are implemented as final methods in Object, so all classes have them.
All three methods can be called only from within a synchronized context.
Unit III- Multithreading in JAVA

• wait() tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).

• notify() wakes up a thread that called wait( ) on the same object.

• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.

Example program for producer and consumer problem

class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try {
wait();
}
catch(InterruptedException e)
{
Unit III- Multithreading in JAVA

System.out.println("Interrupted Exception caught");


}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)

{
System.out.println("InterruptedException caught");

this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable


{

Q q; Producer (Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{

int i = 0;
while(true
)
Unit III- Multithreading in JAVA

{
q.put(i++);
}

}
} //end of Producer

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{

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

{
q.get();
}

}
}//end of Consumer

class PCFixed
{
public static void main(String args[])

{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
---------------------------------------------------------------------------------------------------------------------
Unit III- Multithreading in JAVA

Q9. Suspending, Blocking and Stopping Threads

Whenever we want stop a thread we can stop from running using "stop()" method of
thread class. It's general form will be as follows: Thread. Stop(); This method
causes a thread to move from running to dead state. A thread will also move to
dead state automatically when it reaches the end of its method.
Blocking Thread: A thread can be temporarily suspended or blocked from entering
into the runnable and running state by using the following methods:

sleep() —blocked for specified time


suspend() ----blocked until further orders
wait() --blocked until certain condition occurs

These methods cause the thread to go into the blocked state. The thread will return to
the runnable state when the specified time is elapsed in the case of sleep(), the
resume() method is invoked in the case of suspend(), and the notify() method is
called in the case of wait().

You might also like