0% found this document useful (0 votes)
22 views17 pages

Module5 Notes Multithread

Uploaded by

jj3888097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
22 views17 pages

Module5 Notes Multithread

Uploaded by

jj3888097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

OOPS with JAVA (BCS306A) Module5

Module5
Multithreaded Programming
Enumerations, Type Wrappers and Autoboxing

Multithreaded Programming: The Java Thread Model, The Main Thread, Creating a Thread,
Creating Multiple Threads, Using isAlive() and join(), Thread Priorities, Synchronization,
Interthread Communication, Suspending, Resuming, and Stopping Threads, Obtaining a
Thread’s State.

Enumerations, Type Wrappers and Autoboxing: Enumerations (Enumeration Fundamentals,


The values() and valueOf() Methods), Type Wrappers (Character, Boolean, The Numeric Type
Wrappers), Autoboxing (Autoboxing and Methods, Autoboxing/Unboxing Occurs in
Expressions,Autoboxing/Autoboxing/Unboxing Boolean and Character Values).

Chapter 11, 12

Chapter 1 -Multithreaded Programming


Introduction
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is called
a thread, and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
there are two distinct types of multitasking: process-based and thread-based

A process is, in essence, a program that is executing. Thus, process-based multitasking is the
feature that allows your computer to run two or more programs concurrently. In process based
a program is the smallest unit of code that the scheduler can dispatch.
For example, process-based multitasking enables you to run the Java compiler at the same
time that you are using a text editor or visiting a website.
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks simultaneously.
For instance, a text editor can format text at the same time that it is printing, as long as these
two actions are being performed by two separate 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.

Dept of CS&E,KVGCE,Sullia 1
OOPS with JAVA (BCS306A) Module5

• Multithreading is advantageous due to its lower overhead compared to process-based


multitasking.
• Interthread communication is inexpensive, and context switching from one thread to the
next is lower in cost
• 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.

The Java Thread Model


• Java's runtime system heavily relies on threads to enable asynchronous behaviour,
which helps in utilizing CPU cycles more efficiently.
• Unlike single-threaded systems that use event loops with polling, Java's multithreading
eliminates the need for such mechanisms. In single-threaded environments, blocking
one thread can halt the entire program, leading to inefficiencies and potential domination
of one part over others.
• With Java's multithreading, one thread can pause without affecting other parts of the
program, allowing idle time to be utilized elsewhere.
• This is particularly beneficial for tasks like animation loops, where pauses between
frames don't halt the entire system. Multithreading in Java works seamlessly on both
single-core and multicore systems, with threads sharing CPU time on single-core
systems and potentially executing simultaneously on multicore systems.
• Threads in Java can exist in various states, including running, ready to run, suspended,
blocked, or terminated. Each state represents a different stage of thread execution, with
the ability to suspend, resume, or terminate threads as needed.
• Overall, Java's multithreading capabilities contribute to more efficient and responsive
software development.

Thread States
• Threads exist in several states. Here is a general description. A thread can be running.
• It can be ready to run as soon as it gets CPU time. A running thread can be suspended,
which temporarily halts its activity. A suspended thread can then be resumed, allowing it
to pick up where it left off.
• A thread can be blocked when waiting for a resource. At any time, a thread can be
terminated, which halts its execution immediately. Once terminated, a thread cannot be
Dept of CS&E,KVGCE,Sullia 2
OOPS with JAVA (BCS306A) Module5

resumed.
Thread Priorities
• Java assigns to each thread a priority that determines how that thread should be treated
• with respect to the others.
• Higher-priority threads are given preference during context switches, but priority doesn't
affect the speed of execution.
• The rules that determine when a context switch takes place are simple:
➢ This occurs when explicitly yielding, sleeping, or when blocked. In this scenario,
all other threads are examined, and the highest-priority thread that is ready to
run is given the CPU.
➢ 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.
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.

The Thread Class and the 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.
Thread Methods: Java's Thread class provides various methods for managing threads,
including getName(), getPriority(), isAlive(), join(), run(), sleep(), and start().

The Main Thread


• When a Java program starts up, one thread begins running
immediately. This is usually called the main thread of our program.
• The main thread is important for two reasons:
➢ It is the thread from which other “child” threads will be spawned.
Dept of CS&E,KVGCE,Sullia 3
OOPS with JAVA (BCS306A) Module5

➢ Often, it must be the last thread to finish execution because it performs various
shutdown actions.
• the main thread is created automatically when your program is started, it can be controlled
through a Thread object.
• obtain a reference to it by calling the method currentThread( ), which is a public static
member of Thread.
static Thread currentThread( )
• This method returns a reference to the thread in which it is called

• The sleep( ) method causes the thread from which it is called to suspend execution for the
specified period of milliseconds.

static void sleep(long milliseconds) throws InterruptedException

Creating a Thread

class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread(); Current thread: Thread[main,5,main]
System.out.println("Current thread: " + t); After name change: Thread[My Thread,5,main]
t.setName("My Thread"); 5
4
System.out.println("After name change: " + t);
3
try { 2
for(int n = 5; n > 0; n--) { 1
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}

A thread by instantiating an object of typeThread. Java defines two ways in which this can be
accomplished:
1. You can implement the Runnable interface.
2. You can extend the Thread class, itself.
1. Implementing Runnable
• 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, 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.run( ) establishes the entry point for another,
concurrent thread of execution within your program.

public void run( )

Dept of CS&E,KVGCE,Sullia 4
OOPS with JAVA (BCS306A) Module5

• Instantiating Thread Object: After implementing Runnable, 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.
Example: An example code snippet demonstrates creating and starting a new thread using the
Runnable interface

class NewThread implements Runnable class ThreadDemoerunn


{ {
Thread t; public static void main(String args[])
NewThread() {
{ new NewThread(); // create a new thread
// Create a new, second thread
}
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
}
t.start();
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

2. Extending Thread
• 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.

Dept of CS&E,KVGCE,Sullia 5
OOPS with JAVA (BCS306A) Module5

class NewThread extends Thread


{
Thread t;
NewThread()
{
// Create a new, second thread
super("Demo Thread"); // Create a new, second thread
System.out.println("Child thread using extend : " + this);
start(); // Start the thread
}
}
// This is the entry point for the second thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemoerunn
{
public static void main(String args[])
{
new NewThread();
}
}

Dept of CS&E,KVGCE,Sullia 6
OOPS with JAVA (BCS306A) Module5

Creating Multiple Threads


// Create multiple threads.
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
Thread.sleep(10000);
} catch (InterruptedException e)
{
System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Dept of CS&E,KVGCE,Sullia 7
OOPS with JAVA (BCS306A) Module5

Using isAlive( ) and join( )

• 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 terminate 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.

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.

Dept of CS&E,KVGCE,Sullia 8
OOPS with JAVA (BCS306A) Module5

• Higher-priority threads can preempt lower-priority ones, meaning they can interrupt the
execution of lower- priority threads
• The factors other than a thread’s priority also affect how much CPU time a thread receives.
• When a child thread is started, its priority setting is equal to that of its parent thread.

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()

Dept of CS&E,KVGCE,Sullia 9
OOPS with JAVA (BCS306A) Module5

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 re-enter 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

Need for Synchronization:

• Synchronization is necessary to ensure thread safety, especially when multiple threads


access shared resources concurrently.
• Without synchronization, concurrent access to shared resources can lead to data
corruption, race conditions, and other inconsistencies

Implicit Monitors:

• Key to synchronization in Java is the concept of the monitor(semaphore).


• All objects in Java have their own implicit monitor associated with them.
• 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

Synchronized Keyword

Synchronized Synchronized
method statements

1. Using Synchronized Methods


• Synchronization is easy in Java, because all objects have their own
implicit monitor associated with them.
• To enter an object’s monitor, just call a method that has been
modified with the synchronized keyword.
• While a thread is inside a synchronized method, all other threads
that try to call it on the same instance have to wait.

Dept of CS&E,KVGCE,Sullia 10
OOPS with JAVA (BCS306A) Module5

• To exit the monitor and relinquish control of the object to the next
waiting thread, the owner of the monitor simply returns from the
synchronized method.

Synchronized type mehod_name(param_list)


The example program consists of three classes: Callme, Caller, and Synch.
• The Callme class has a method call() which prints a message inside square brackets and
then pauses the thread for one second using Thread.sleep(1000).T
• The Caller class takes a reference to an instance of Callme and a message string. It
creates a new thread that calls the run() method which in turn calls the call() method on
the Callme instance.
• The Synch class creates a single instance of Callme and three instances of Caller, each
with a unique message string. All Caller instances share the same Callme instance.

Dept of CS&E,KVGCE,Sullia 11
OOPS with JAVA (BCS306A) Module5

2. The synchronized Statement


• Imagine that you want to synchronize access to objects of a class that was not designed
for multithreaded access. That is, the class does not use synchronized methods and this
class was not created by you, but by a third party, and you do not have access to the
source code.
• So not possible for you to add synchronized to the appropriate methods within the class
• the solution to this problem is simply put calls to the methods defined by this class inside
a synchronized block.

synchronized ( object )
{
// statements to be synchronized
}

• Here, object is a reference to the object being synchronized.


• A synchronized block ensures that a call to a method that is a
member of object will take place only after the object’s monitor has
been entered by the calling thread.

Dept of CS&E,KVGCE,Sullia 12
OOPS with JAVA (BCS306A) Module5

Interthread Communication
consider the classic queuing problem, where one thread is producing some data and another
is consuming it. To make the problem more interesting, suppose that the producer has to wait
until the consumer is finished before it generates more data. In a polling system, the consumer
would waste many CPU cycles while it waited for the producer to produce. Once the producer
was finished, it would start polling, wasting more CPU cycles waiting for the consumer to
finish, and so on. Clearly, this situation is undesirable.
Solution is: it relies upon some form of interthread communication in which one thread can
notify another that it is blocked, and be notified that it can resume execution.
Method Definitions:

Dept of CS&E,KVGCE,Sullia 13
OOPS with JAVA (BCS306A) Module5

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

Dept of CS&E,KVGCE,Sullia 14
OOPS with JAVA (BCS306A) Module5

class PCFixed {
public static void main(String[] args) {
Q q = new Q();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
// Start the threads.
p.t.start();
c.t.start();
System.out.println("Press Control-C to stop.");
}
}

• Inside get( ), wait( ) is called. This causes its execution to suspend until Producer
notifies you that some data is ready.
• When this happens, execution inside get( ) resumes. After the data has been obtained,
get( ) calls notify( ).
• This tells Producer that it is okay to put more data in the queue.
• Inside put( ), wait( ) suspends execution until Consumer has removed the item from
the queue.
• When execution resumes, the next item of data is put in the queue, and notify( ) is
called. This tells Consumer that it should now remove it.

Suspending, Resuming, and Stopping Threads


Deprecated Methods:

• In early versions of Java (prior to Java 2), thread suspension, resumption, and
termination were managed using suspend(), resume(), and stop() methods defined by
the Thread class.
• However, these methods were deprecated due to potential issues and risks they posed,
such as causing system failures and leaving critical data structures in corrupted states

Reasons for Deprecation:

• suspend(): Can cause serious system failures, as it doesn't release locks on critical
data structures, potentially leading to deadlock.
Dept of CS&E,KVGCE,Sullia 15
OOPS with JAVA (BCS306A) Module5

• resume(): Deprecated as it requires suspend() to work properly.


• stop(): Can cause system failures by leaving critical data structures in corrupted states.

Alternative Approach:

• Instead of using deprecated methods, threads should be designed to periodically


check a flag variable to determine whether to suspend, resume, or stop their own
execution.
• Typically, a boolean flag variable is used to indicate the execution state of the thread.If
the flag is set to "running," the thread continues to execute. If it's set to "suspend," the
thread pauses. If it's set to "stop," the thread terminates.

Example Using wait() and notify():

• The wait() and notify() methods inherited from Object can be used to control the
execution of a thread.
• An example provided demonstrates how to use these methods to control thread
execution.
• It involves a boolean flag (suspendFlag) to control the execution of the thread.
• The run() method periodically checks suspendFlag, and if it's true, the thread waits.
Methods mysuspend() and myresume() are used to set and unset the flag and notify
the thread to wake up.

Obtaining a Thread’s State


• We can obtain the current state of a thread by calling the getState( ) method defined
by Thread.
• It is shown here: Thread.State getState( )
• It returns a value of type Thread.
• State that indicates the state of the thread at the time at which the call was made. State
is an enumeration defined by Thread.
• Here are the values that can be returned by getState( )

Dept of CS&E,KVGCE,Sullia 16
OOPS with JAVA (BCS306A) Module5

• 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 ts = thrd.getState();

if(ts ==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.

Dept of CS&E,KVGCE,Sullia 17

You might also like