Module 5
Module 5
Module -5
Multithreaded Programming
➢ Multithreading in Java allows for concurrent execution of multiple parts of a program, known as
threads.
➢ This contrasts with process-based multitasking, where each program is a separate unit, whereas
threads share the same address space and belong to the same process.
➢ Multithreading is advantageous due to its lower overhead compared to process-based multitasking.
➢ It helps in maximizing processing power by minimizing idle time, especially in interactive and
networked environments where tasks like data transmission and user input are slower compared to
CPU processing speed.
➢ Multithreading enables more efficient use of available resources and smoother program execution by
allowing other threads to run while one is waiting.
Thread Priorities
Thread Priorities : Java assigns each thread a priority to determine its relative importance. Higher-priority
threads are given preference during context switches, but priority doesn't affect the speed of execution.
Thread States: Threads can be in various states like running, ready to run, suspended, blocked, or terminated.
These states govern the behavior of threads in the system.
Synchronization: Java provides mechanisms like monitors to enforce synchronicity between threads, ensuring
that shared resources are accessed safely. Synchronization is achieved through the use of synchronized
methods and blocks.
Messaging: Java facilitates communication between threads through predefined methods that all objects have.
This messaging system allows threads to wait until they are explicitly notified by another thread.
Thread Class and Runnable Interface : Java's multithreading system is built around the Thread class and
the Runnable interface. Threads can be created either by extending the Thread class or implementing the
Runnable interface.
Main Thread : Every Java program starts with a main thread, which is automatically created. The main thread
is crucial for spawning other threads and often performs shutdown actions at the end of the program.
• Thread Methods : Java's Thread class provides various methods for managing threads, including getName(),
getPriority() , isAlive(), join() , run(), sleep() , and start() .
Creating a Thread
Implementing Runnable Interface: To create a thread, you implement the Runnable interface in a class. This
interface abstracts a unit of executable code and requires implementing a single method called run().
Runnable's run() Method: Inside the run() method, you define the code that constitutes the new thread. This
method can call other methods, use other classes, and declare variables just like the main thread can.
Instantiating Thread Object: After implementing Runnable, you instantiate an object of type Thread within that
class. The Thread constructor requires an instance of a class that implements Runnable and a name for the
thread.
Starting the Thread: The new thread doesn't start running until you call its start() method. This method initiates
a call to run(), effectively starting the execution of the new thread.
Object Oriented Programming with JAVA(BCS306A) Module 5
Example: An example code snippet demonstrates creating and starting a new thread:
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
}
class ThreadDemo {
public static void main(String[] args) {
NewThread nt = new NewThread(); // create a new thread
nt.t.start(); // Start the thread
// Main thread continues its execution
// ...
}
}
Extending Thread
Extending Thread Class: To create a thread, you create a new class that extends the Thread class. The
extending class must override the run() method, which serves as the entry point for the new thread.
Constructor Invocation: Inside the constructor of the extending class, you can invoke the constructor of the
Thread class using super() to specify the name of the thread.
Starting the Thread: After creating an instance of the extending class, you call the start() method to begin
execution of the new thread.
Example:
class ExtendThread {
public static void main(String[] args) {
NewThread nt = new NewThread(); // create a new thread
nt.start(); // start the thread
// Main thread continues its execution
// ...
}
}
Creating Multiple Threads
NewThread(String
threadname) { name =
threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
}
class MultiThreadDemo {
public static void main(String[] args) { NewThread
nt1 = new NewThread("One"); NewThread nt2 =
new NewThread("Two"); NewThread nt3 = new
NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) { System.out.println("Main
thread Interrupted");
}
Sample output from this program is shown here. (Your output may vary based upon
the specific execution environment.)
exiting.
Three
exiting
Object Oriented Programming with JAVA(BCS306A) Module 5
Main thread exiting.
• isAlive() Method:
• Defined by the Thread class.
• Returns true if the thread upon which it is called is still running.
• Returns false otherwise.
• Occasionally useful for checking the status of a thread.
• join() Method:
• Also defined by the Thread class.
• Waits until the thread on which it is called terminates.
• The calling thread waits until the specified thread joins it.
• Additional forms of join() allow specifying a maximum amount of time to wait for the specified thread to
terminate.
• Usage:
• join() is commonly used to ensure that one thread waits for another thread to finish its execution.
• This is particularly useful when you want the main thread to finish last or when you need to synchronize the
execution of multiple threads.
• Example:
• An improved version of the example code can use join() to ensure that the main thread is the last to stop.
• Additionally, isAlive() can be used to check if a thread is still running.
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name); System.out.println("New
thread: " + t);
}
class DemoJoin {
public static void main(String[] args) { NewThread
nt1 = new NewThread("One"); NewThread nt2 =
new NewThread("Two"); NewThread nt3 = new
NewThread("Three");
Thread Priorities
• Thread Priorities :
• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
• In theory, higher-priority threads get more CPU time than lower-priority threads over a given period of time.
• Higher-priority threads can preempt lower-priority ones, meaning they can interrupt the execution of lower-
priority threads.
Object Oriented Programming with JAVA(BCS306A) Module 5
• Equal Priority Threads:
• In theory, threads of equal priority should get equal access to the CPU.
• However, Java is designed to work in various environments, and the actual behavior may differ depending
on the operating system and multitasking implementation.
• To ensure fairness, threads that share the same priority should yield control occasionally, especially in
nonpreemptive environments.
• Setting Thread Priority:
• Use the setPriority() method to set a thread's priority.
• Syntax: void setPriority(int level)
• The level parameter specifies the new priority setting for the thread, and it must be within the range of
MIN_PRIORITY and MAX_PRIORITY, currently 1 and 10, respectively.
• To return a thread to default priority, use NORM_PRIORITY, which is currently 5.
• Getting Thread Priority:
• Use the getPriority() method to obtain the current priority setting of a thread.
• Syntax: int getPriority()
• Implementation Considerations:
• Implementations of Java may have different behaviors when it comes to scheduling and thread priorities.
• To ensure predictable and cross-platform behavior, it's advisable to use threads that voluntarily give up CPU
time.
Synchronization
➢ 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. A monitor is an object that is
used as a mutually exclusive lock.
➢ 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.
➢ You can synchronize your code in either of two ways. Both involve the use of the
➢ synchronized keyword, and both are examined here.
class Synch {
public static void main(String[] args) { Callme
target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized"); Caller
ob3 = new Caller(target, "World");
[Hello[Synchronized[World]
]
]
Interthread Communication
Interprocess communication using wait() , notify() , and notifyAll() methods in Java:
• Purpose:
• These methods provide a means for threads to communicate and coordinate their activities without using
polling, which can waste CPU cycles.
• Method Definitions:
• 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() or notifyAll().
• notify() : Wakes up a single thread that previously called wait() on the same object.
• notifyAll(): Wakes up all threads that previously called wait() on the same object. One of the threads will be
granted access.
• All three methods are declared within the Object class and can only be called from within a synchronized
context.
Additional Forms of wait():
• Additional forms of the wait() method exist that allow you to specify a period of time to wait.
• Spurious Wakeups:
• In rare cases, a waiting thread could be awakened due to a spurious wakeup, where wait() resumes without
notify() or notifyAll() being called. To handle this, calls to wait() are often placed within a loop that checks
the condition on which the thread is waiting.
• Best Practices:
• The Java API documentation recommends using a loop to check conditions when waiting, especially due to
the possibility of spurious wakeups.
Object Oriented Programming with JAVA(BCS306A) Module 5
class Q {
int n;
Producer(Q q)
{ this.q = q;
t = new Thread(this, "Producer");
}
while(true) {
q.put(i++);
}
}
}
Consumer(Q q) {
this.q = q;
t = new Thread(this, "Consumer");
}
Object Oriented Programming with JAVA(BCS306A) Module 5
class PC {
public static void main(String[] args) { Q q =
new Q();
Producer p = new Producer(q);
Consumer c = new
Consumer(q);
Although the put( ) and get( ) methods on Q are synchronized, nothing stops the
producer from overrunning the consumer, nor will anything stop the consumer from
consuming the same queue value twice. Thus, you get the erroneous output shown here
(the exact output will vary with processor speed and task load):
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
Object Oriented Programming with JAVA(BCS306A) Module 5
} catch(InterruptedException e) { System.out.println("InterruptedException
caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
Producer(Q q)
{ this.q = q;
t = new Thread(this, "Producer");
}
Object Oriented Programming with JAVA(BCS306A) Module 5
while(true) {
q.put(i++);
}
}
}
Consumer(Q q) {
this.q = q;
t = new Thread(this, "Consumer");
}
class PCFixed {
public static void main(String[] args) { Q q =
new Q();
Producer p = new Producer(q);
Consumer c = new
Consumer(q);
Put: 1
Object Oriented Programming with JAVA(BCS306A) Module 5
Got: 1
Put: 2
Got: 2
Object Oriented Programming with JAVA(BCS306A) Module 5
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Object Oriented Programming with JAVA(BCS306A) Module 5
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
}
Object Oriented Programming with JAVA(BCS306A) Module 5
class SuspendResume {
public static void main(String[] args) { NewThread
ob1 = new NewThread("One"); NewThread ob2
= new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One"); Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two"); Thread.sleep(1000);
Object Oriented Programming with JAVA(BCS306A) Module 5
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Value State
BLOCKED A thread that has suspended execution because it is waiting to acquire a
lock.
NEW A thread that has not begun execution.
RUNNABLE A thread that either is currently executing or will execute when it
gains access to the CPU.
TERMINATED A thread that has completed execution.
TIMED_WAITI A thread that has suspended execution for a specified period of time,
NG such as when it has called sleep( ). This state is also entered when a
timeout version of wait( ) or join( ) is called.
WAITING A thread that has suspended execution because it is waiting for
some action to occur. For example, it is waiting because of a call to
a non- timeout version of wait( ) or join( ).
Object Oriented Programming with JAVA(BCS306A) Module 5
Part I
The above diagram shows how the various thread states relate.
Given a Thread instance, you can use getState( ) to obtain the state of a thread. For example, the
following sequence determines if a thread called thrd is in the RUNNABLE state at the time getState( ) is
called:
Thread.State.RUNNABLE) // ...
It is important to understand that a thread’s state may change after the call to getState( ).
Thus, depending on the circumstances, the state obtained by calling getState( ) may not reflect the actual
state of the thread only a moment later. For this (and other) reasons, getState( ) is not intended to
provide a means of synchronizing threads. It’s primarily used for debugging or for profiling a thread’s
run-time characteristics.