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

Multi Threading (1)

The document explains the concepts of multithreading and multiprocessing in Java, highlighting their differences, advantages, and how Java manages threads. It covers thread states, priorities, creation methods, synchronization, inter-thread communication, and thread management techniques. Additionally, it discusses the importance of the main thread and provides insights into thread control and communication mechanisms in Java.

Uploaded by

Pratheek H B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Multi Threading (1)

The document explains the concepts of multithreading and multiprocessing in Java, highlighting their differences, advantages, and how Java manages threads. It covers thread states, priorities, creation methods, synchronization, inter-thread communication, and thread management techniques. Additionally, it discusses the importance of the main thread and provides insights into thread control and communication mechanisms in Java.

Uploaded by

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

Multithreaded Programming

Multithread vs Multiprocessing
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


• Allows computer to run two or more programs concurrently
• In Process-based Multitasking, a program is the smallest unit of code that
can be dispatched by the scheduler.
• 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.
• Process-based Multitasking is not under the control of java
2) Thread-based Multitasking (Multithreading)
• A single program can perform two or more tasks
simultaneously.
• In thread-based Multitasking, a thread is the smallest
unit that can be dispatched by the scheduler.
• Threads share the same address space.
• A thread is lightweight.
• Less overhead than mutiprocessing
• Cost of communication between the thread is low
• Multithreading is under the control of java
JAVA thread model

• Multithreading is a Java feature that allows


concurrent execution of two or more parts of a
program for maximum utilization of CPU.
• Each part of such program is called a thread. So,
threads are light-weight processes within a process.
• Multithreading enables to write efficient programs
that make maximum use of CPU, because idle time
can be kept to minimum.
• A thread is a lightweight sub process, 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 prev 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.
• All class libraries are designed with multithreading in mind
• Java uses threads to enable the entire environment to be synchronous.
• Example: Read or write even to a local file system is much slower pace
than they can be processed by the CPU. In single thread system
whenever there is read until event handler returns , nothing else can
happen.
• This wastes CPU time. This may even result in one part of program
dominating the system and preventing any other events from being
processed.
• Whereas in multithreading, the idle time created when thread reads
data from network or waits for user input can be utilized elsewhere.
Thread States
• Thread can have several states:
• It can be ready to run as soon as it gets CPU time.
• A thread can be running
• Thread can be suspended, which temporarily suspends its
activity
• A suspended thread can be resumed allowing it to pick up
where it left off.
• A thread can be blocked when waiting for a resource.
• Any time thread can be terminated, which halts its
execution immediately. Once threaded cannot be resumed.
Thread Priorities
• Java assigns priority to each thread that determines how that thread should
be treated with respect to the others.
• Java scheduler assigns processor to threads based on the priority.
• Priority can either be given by JVM while creating the thread or it can be
given by programmer explicitly.
• Thread priorities are integers that specify the relative priority of one thread to
another.
• 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. In practice, the amount of CPU time that a thread gets often
depends on several factors besides its priority.
• 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)
• 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.
• obtain the current priority setting by calling the getPriority( ) method of Thread,
• final int getPriority( )
• Thread class for priority.
• public static int MIN_PRIORITY: This is minimum priority that a thread can have.
Value for this is 1.
public static int NORM_PRIORITY: This is default priority of a thread if do not
explicitly define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this
is 10.

• public final int getPriority()


• public final void setPriority(int newPriority)
• Thread with highest priority will get execution chance prior to other threads.
Suppose there are 3 threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will
execute first based on maximum priority 6 after that t1 will execute and then t3.
• Default priority for main thread is always 5, it can be changed later. Default priority
for all other threads depends on the priority of parent thread
• If two threads have same priority then we can’t expect which thread will execute
first. It depends on thread scheduler’s algorithm(Round-Robin, First Come First
Serve, etc)
The Thread class defines several methods that
help manage threads

Method Meaning

getName Obtain a thread’s name.

getPriority Obtain a thread’s priority.

isAlive Determine if a thread is still running

Join Wait for a thread to terminate.

run Entry point for the thread.

Sleep Suspend a thread for a period of time.

start Start a thread by calling its run method.


The Main Thread
• When a Java program starts up, one thread begins
running immediately. This is usually called the main
thread of your program, because it is the one that is
executed when your program begins.
• The main thread is important for two reasons:
• It is the thread from which other “child” threads will
be spawned*.
• Often, it must be the last thread to finish execution
because it performs various Shut down actions.
• *Spawn in computing refers to a function that loads
and executes a new child process.
• Although the main thread is created automatically when your
program is started, it can be controlled through a Thread object.
• To do so, you must 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 you have a reference to the main thread, you can control it
just like any other thread.
• The sleep( ) method causes the thread from which it is called to
suspend execution for the specified period of milliseconds. Its
general form is shown here:
• static void sleep(long milliseconds) throws InterruptedException
Creating thread in Java

• Threads can be created by using two mechanisms :

1. Implementing the Runnable Interface


• The easiest way to create a thread is to create a class that
implements the Runnable interface.
• Runnable abstracts a unit of executable code.
• You can construct a thread on any object that implements
Runnable.
• To implement Runnable, a class need only implement a
single method called run( ), which is declared like this:
• public void run( )
• Inside run( ), you will define the code that
constitutes the new thread. It is important to
understand that run( ) can call other methods, use
other classes, and declare variables, just like the
main thread can.
• you will instantiate an object of type
• After you create a class that implements
Runnable ,Thread from within that class. Thread
defines several constructors
• Inside NewThread’s constructor, a new Thread
object is created by the following statement:
• t = new Thread(this, "Demo Thread");
2. Extending the Thread class
• The second way to create a thread is to create
a new class that extends Thread, and then to
create an instance of that class. The extending
class must override the run( ) method, which
is the entry point for the new thread. It must
also call start( ) to begin execution of the new
thread.
How can one thread know when another thread has ended?

• Java multi-threading provides two ways to find whether a thread has finished

• isAlive() : call to isAlive() on thread to tests if this thread is alive.

• Final Boolean isAlive()

• If method returns true if the thread called upon is still running’


Else returns false

• A thread is alive if it has been started and has not yet died. This method is
used to find out if a thread has actually been started and has yet not
terminated.
2.Join()
The method more commonly used to wait for a thread to finish is called join()
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates
Additional forms of join( ) allow you to specify a maximum amount of time
that you want to wait for the specified thread to terminate.
Here is an improved version of the preceding example that uses join( ) to
ensure that the
main thread is the last to stop
try
{
/*System.out.println("Child Thread Status " +
A.t.isAlive());
A.t.join();
System.out.println("Child Thread Status " +
A.t.isAlive());*/
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 (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 re-enter the same
monitor if it so desires.
• Instead, to synchronize threads, your programs need to utilize operating
system primitives. Fortunately, because Java implements synchronization
through language elements, most of the complexity associated with
synchronization has been eliminated.
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.
• 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.
The synchronized Statement
• Calls to the methods defined by this class inside a
synchronized block.
• This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
• A synchronized block ensures that a call to a method
that is a member of object occurs only after the current
thread has successfully entered object’s monitor.
Inter-thread Communication

• The threads can communicate with each other through wait() notify() and notifyAll() methods
in Java.
• These are final methods defined in the Object class and can be called only from within
a synchronized context.
• The wait() method causes the current thread to wait until another thread invokes
the notify() or notifyAll() methods for that object.
• The notify() method wakes up a single thread that is waiting on that object’s monitor.
• The notifyAll() method wakes up all threads that are waiting on that object’s monitor.
• A thread waits on an object’s monitor by calling one of the wait() method. These methods can
throw IllegalMonitorStateException if the current thread is not the owner of the object’s
monitor.
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()
• Although wait( ) normally waits until notify( ) or notifyAll( )

• notify() and notifyAll() methods with wait() method are used to


for communication between the threads. A thread which goes
into waiting state by calling wait() method will be in waiting state
until any other thread calls either notify() or notifyAll() method
on the same object.
• Sun recommends that calls to wait( ) should take place within a
loop that checks the condition on which the thread is waiting
• Producer, the threaded object that is producing queue entries;
Consumer, the threaded
• object that is consuming queue entries
Suspending, Resuming, and Stopping
Threads
• Final void suspend()
• This method puts a thread in the suspended state and can be resumed
using resume() method.
• Final void resume()
• This method resumes a thread, which was suspended using suspend()
method.
• final void stop()
• This method stops a thread completely.
• Prior to Java 2, a program used suspend( ) and resume( ), which are
methods defined by
• Thread, to pause and restart the execution of a thread.
• Once a thread has been stopped, it cannot be restarted using resume( ).
• suspend( ) method was deprecated by Java 2
several years ago. This was done because
suspend( ) can sometimes cause serious system
failures.
• The resume( ) method is also deprecated. It does
not cause problems, but cannot be used without
the suspend( ) method as its counterpart.
• The stop( ) method of the Thread class, too, was
deprecated by Java 2. This was done because this
method can sometimes cause serious system
failures.
• Instead to previous approach, a thread is designed so
that the run( ) method periodically checks to
determine whether that thread should suspend,
resume, or stop its own execution.
• Typically, this is accomplished by establishing a flag
variable that indicates the execution state of the
thread.
• As long as this flag is set to “running,” the run( )
method must continue to let the thread execute.
• If this variable is set to “suspend,” the thread must
pause.
• If it is set to “stop,” the thread must terminate.

You might also like