0% found this document useful (0 votes)
25 views19 pages

Module-5(Oops With Java)

Pdf
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
25 views19 pages

Module-5(Oops With Java)

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

MODULE-5

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.
 However, there are two distinct types of multitasking: process-based and thread-based.
 A process-based multitasking is the feature that allows your computer to run two or more
programs concurrently.
 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 web site.
 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.
 Multithreading enables you to write efficient programs that make maximum use of the
processing power available in the system.
 Multithreading helps you reduce this idle time because another thread can run when one is
THE JAVA THREAD MODEL
 Java's runtime system heavily relies on threads to enable asynchronous behavior, 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 PRIORITIES
 Thread priorities are integers that specify the relative priority of one thread to another.
 A thread’s priority is used to decide when to switch from one running thread to the next.
This is called a context switch.
 The rules that determine when a context switch takes place are simple:
 A thread can voluntarily relinquish control:
 A thread can be preempted by a higher-priority thread:

 Thread States :Threads can be in various states like running, ready to run, suspended, blocked, or
terminated. T
 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.

 The thread class defines the following methods to manage the threads.
THE MAIN THREAD

 When a Java program starts up executing, one of the thread begins running immediately known as
the main thread.
 The main thread is important for two reasons:
 It is the thread from which other “child” threads will be spawned.
 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.
 To control the thread, obtain a reference to it by calling the method currentThread( ), which is a
public static member of Thread.
Its general form is shown here:
static Thread currentThread( )

 This method returns a reference to the thread in which it is called.

 Once we have a reference to the main thread, we can control it just like any other thread.
Creating thread

 A thread can be created by instantiating an object of type Thread.


 Java defined two ways to create a thread:
1. By implementing Runnable interface
2. By extending Thread class
IMPLEMENTING RUNNABLE

 The easiest way to create a thread is to create a class that implements the
Runnable interface. Which is an abstracts a unit of executable code.
 To implement Runnable, a class need only implement a single method called
run( ), which is declared like this:
public void run( )
 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.
 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.
 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.
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.
 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.
 After creating an instance of the extending class, you call the start() method to begin execution of the
new thread.
CREATING MULTIPLE THREADS
Using isalive() and join()
How can one thread know whether another thread has ended or not?
There two ways to determine whether a thread has finished
1. isAlive()
2. 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:
 join() is commonly used to ensure that one thread waits for another thread to finish its execution.
 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.
 This is particularly useful when you want the main thread to finish last or when you need to synchronize
the execution of multiple threads.
TREAD 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.
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.
CONTINUATION

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, it has to ensure
that the resource will be used by only one thread at a time. The process 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.
USING SYNCHRONIZED METHODS

You might also like