Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java_multithreading

The document provides an overview of multithreading in Java, explaining its basics, differences from multitasking, and the Java thread model. It covers thread life cycles, creation methods, thread priorities, synchronization, and inter-thread communication. Additionally, it discusses the advantages of multithreading and addresses potential issues like deadlocks.

Uploaded by

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

Java_multithreading

The document provides an overview of multithreading in Java, explaining its basics, differences from multitasking, and the Java thread model. It covers thread life cycles, creation methods, thread priorities, synchronization, and inter-thread communication. Additionally, it discusses the advantages of multithreading and addresses potential issues like deadlocks.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

1

Multithreading
Multithreading:
2

 Multithreading Basics
 Differences between multithreading and multitasking,
 thread life cycle,
 creating threads,
 synchronizing threads,
 daemon threads,
 thread groups
Multithreading:
3
 Unlike many other computer languages, 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.
 You are almost certainly acquainted with multitasking, because it is
supported by virtually all modern operating systems. However, there
are two distinct types of multitasking: process based and thread-
based.
Multithreading:
4
❑PROCESS-BASED MULTITASKING
• A process is a program that is executing. Thus, processbased multitasking is the feature
that allows our 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.

• In process based multitasking, a program is the smallest unit of code that can be
dispatched by the scheduler.

❑THREAD-BASED MULTITASKING
• 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.
Multithreading:
5
Differences between Multiprocessing and Multithreading

Multiprocessing Multithreading
More than one process running simultaneousy More than one thread running simultaneously
Its part of a program Its part of a program
It’s a heavy wait process It’s a light wait process
Process is divided into threads Threads are divided into sub-threads
There is no communications between Within the process threads are communicated
processors directly
Multithreading:
6
❑The Java Thread Model
• The Java run-time system depends on threads for many things, and all the class
libraries are designed with multithreading in mind. In fact, Java uses threads to
enable the entire environment to be asynchronous. This helps reduce inefficiency
by preventing the waste of CPU cycles.

• The value of a multithreaded environment is best understood in contrast to its


counterpart. Single-threaded systems use an approach called an event loop with
polling.

• The benefit of Java’s multithreading is that the main loop/polling mechanism is


eliminated. One thread can pause without stopping other parts of your program.
Multithreading:
7
❑The Java Thread Model ...
• Eg: The idle time created when a thread reads data from a network or waits for user input can be
utilized elsewhere.

• Multithreading allows animation loops to sleep for a second between each frame without causing
the whole system to pause. When a thread blocks in a Java program, only the single thread that is
blocked pauses. All other threads continue to run.

Advantage of Java Multithreading:


• It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

• You can perform many operations together so it saves time.

• Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Multithreading:
8
❑The Java Thread Model ...
Life Cycle of a Thread:

• Threads exist in several states. 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 suspends 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 resumed.
Multithreading:
9
•The Java Thread Model ...
•Life Cycle of a Thread: ...
Multithreading: • The Java Thread Model ...
10
Thread Priorities
• Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others.
• Thread priorities are integers that specify the relative priority of one thread to
another. As an absolute value, a priority is meaningless; a higher-priority thread
doesn’t run any faster than a lower-priority thread if it is the only thread running.

• Instead, 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. This is done by explicitly yielding, sleeping, or blocking on
pending I/O. 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 higherpriority thread.
Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.
Multithreading:
11
• The Java Thread Model ...

Thread Priorities ...


• In cases where two threads with the same priority are competing for CPU cycles,
the situation is a bit complicated. For operating systems such as Windows, threads
of equal priority are time-sliced automatically in round-robin fashion. For other
types of operating systems, threads of equal priority must voluntarily yield control
to their peers. If they don’t, the other threads will not run.

• Java thread priorities are in the range between MIN_PRIORITY (a constant of


1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).
Multithreading:
12
• The Java Thread Model ...
Synchronization

• Because multithreading introduces an asynchronous behavior to your programs,


there must be a way for you to enforce synchronicity when you need it.

• For example, if you want two threads to communicate and share a complicated data
structure, such as a linked list, you need some way to ensure that they don’t conflict
with each other. That is, you must prevent one thread from writing data while
another thread is in the middle of reading it.

• For this purpose, Java implements an elegant twist on an age-old model of inter-
process synchronization: the monitor.
• The monitor is a control mechanism first defined by C.A.R. Hoare.
Multithreading:
13
• The Java Thread Model ...
Synchronization ...

• A monitor is a very small box that can hold only one thread. Once a thread enters a
monitor, all other threads must wait until that thread exits the monitor. In this way, a
monitor can be used to protect a shared asset from being manipulated by more than
one thread at a time.

• Most multithreaded systems expose monitors as objects that your program must
explicitly acquire and manipulate.
• The synchronization is mainly used to, To prevent thread interference.
 To prevent consistency problem.
Multithreading:
14
• The Java Thread Model ...
Synchronization ...
• Java provides a cleaner solution. There is no class “Monitor”; instead,
each object has its own implicit monitor that is automatically entered
when one of the object’s synchronized methods is called.

• Once a thread is inside a synchronized method, no other thread can


call any other synchronized method on the same object. This
enables you to write very clear and concise multithreaded code,
because synchronization support is built into the language.
Multithreading:
15
• The Java Thread Model ...
The Thread Class and the Runnable Interface
• Java’s multithreading system is built upon the Thread class, its
methods, and its companion interface, Runnable.
• Thread encapsulates a thread of execution. Since you can’t directly
refer to the ethereal state of a running thread, you will deal with it
through its proxy, the Thread instance that spawned it.
• To create a new thread, your program will either extend Thread or
implement the Runnable interface.
Multithreading: The Java Thread Model ...
16
❑The Thread Class and the Runnable Interface ...
The Thread class defines several methods that help manage threads
Multithreading: The Main thread
17
• 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 shutdown
actions.
• 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.
• The General form of the method currentThread( )
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.
Multithreading:
18
Multithreading:
19
• In this program, a reference to the current thread (the main thread, in this case) is
obtained by calling currentThread( ), and this reference is stored in the local
variable t.
• Next, the program displays information about the thread. The program then calls
setName( ) to change the internal name of the thread. Information about the thread
is then redisplayed.
• Next, a loop counts down from five, pausing one second between each line . The
pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies
the delay period in milliseconds.
• Notice the try/catch block around this loop. The sleep( ) method in Thread might
throw an InterruptedException. This would happen if some other thread wanted to
interrupt this sleeping one.
• This example just prints a message if it gets interrupted . In a real program, you
would need to handle this differently .
Multithreading:
20
• Notice the output produced when t is used as an argument to println( ).
• This displays, in order: the name of the thread, its priority, and the
name of its group. By default, the name of the main thread is main. Its
priority is 5, which is the default value, and main is also the name of
the group of threads to which this thread belongs .
• A thread group is a data structure that controls the state of a collection
of threads as a whole.
• After the name of the thread is changed, t is again output. This time,
the new name of the thread is displayed.
Multithreading:
21
❑ Thread life cycle
•As the process has several states, similarly a thread exists in several states. A thread can be in the following states:

o Ready to run (New): First time as soon as it gets CPU time.


o Running: Under execution.
o Suspended: Temporarily not active or under execution.
o Blocked: Waiting for resources.
o Resumed: Suspended thread resumed, and start from where it left off.
o Terminated: Halts the execution immediately and never resumes.
Multithreading:
22
• Creating a Thread
➢Implementing Runnable

➢Extending Thread

➢Choosing an Approach

Creating a Thread
• One can create a thread by instantiating an object of type Thread.
• Java defines two ways in which thread can be accomplished: by
implementing the Runnable interface and by extending the Thread
class.
Multithreading:
23

❑Creating a Thread ...


Implementing Runnable:
• 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( )


Multithreading:
24
• 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.

• The only difference is that run( ) establishes the entry point for another, concurrent thread
of execution within your program. This thread will end when run( ) returns.
• After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will
use is shown here: Thread(Runnable threadOb, String threadName)

• After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).

• The start( ) method is shown here: void start( )


Multithreading:
25
Implementing Runnable: ...
Multithreading:
26
Extending Thread:

• 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.
Multithreading:
27
Multithreading:
28
Choosing an Approach:
• At this point, you might be wondering why Java has two ways to create
child threads, and which approach is better. The answers to these questions
turn on the same point.

• The Thread class defines several methods that can be overridden by a


derived class. Of these methods, the only one that must be overridden is
run( ). This is, of course, the same method required when you implement
Runnable.
• Many Java programmers feel that classes should be extended only when
they are being enhanced or modified in some way. So, if you will not be
overriding any of Thread’s other methods, it is probably best simply to
implement Runnable.
Multithreading:
29
Multithreading:
30
Thread Priorities:
Multithreading:
31
Thread synchronization ...
Multithreading:
32
❑ Inter-thread communication
• Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
• Cooperation (Inter-thread communication) is a mechanism in which a
thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.
• It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()
Multithreading:
33
•These methods have been implemented as final methods in Object, so
they are available in all the classes.
•All three methods can be called only from within a synchronized
context.
Multithreading:
34
Multithreading:
35
Deadlocks for threads
 Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting
for each other to release the lock, the condition is called deadlock.

 Deadlock describes a situation where two or more threads are blocked forever, waiting
for each other. Deadlock occurs when multiple threads need the same locks but obtain
them in different order. A Java multithreaded program may suffer from the deadlock
condition because the synchronized keyword causes the executing thread to block while
waiting for the lock, or monitor, associatedwith the specifiedobject.
Multithreading:
Deadlocks for threads ...DeadlockSituation 36

When you compile and execute above


program, you find a deadlock situation and
below is the output produced by the program:

Thread1: Holdinglock1...
Thread2: Holdinglock2...
Thread1: Waitingfor lock 2...
Thread2: Waitingfor lock 1...

The program will hang forever because


neither of the threads in position to proceed
and waiting for each other to release the lock,
so you can come out of the program by
pressing CTRL-C.
Multithreading:
37
Deadlocks for threads ... Solution

So, just changing the order of the locks prevent the program in
going deadlock situation and completes with the following result:

Thread1: Holdinglock1...
Thread1: Waitingfor lock 2...
Thread1: Holdinglock1 & 2...
Thread2: Holdinglock1...
Thread2: Waitingfor lock 2...
Thread2: Holdinglock1 & 2...
Multithreading:
38
❑ Daemon Threads:
In Java, daemon threads are a type of thread that runs in the background to perform tasks that
support the main application.

They are typically used for services such as garbage collection, event handling, or other
background tasks that do not require the application to remain alive.

❑ Key Characteristics of Daemon Threads:


 Background Execution: Daemon threads run in the background and do not
prevent the JVM from exiting when the program finishes executing. If only
daemon threads are left running, the JVM will shut down.
 Creation: You can create a daemon thread by calling the setDaemon(true)
method on a Thread instance before starting it.
Multithreading:
39
➢ Priority: Daemon threads typically have lower priority than user
threads, but this is not guaranteed. They can be set to different
priority levels like any other thread.
➢ Use Cases: Common use cases include:
•Periodic cleanup tasks.
•Monitoring services.
•Background data processing.
Multithreading:
Using Multithreading 40
• The key to utilizing Java’s multithreading features effectively is to think
concurrently rather than serially. For example, when you have two
subsystems within a program that can execute concurrently, make them
individual threads.
• With the careful use of multithreading, you can create very efficient
programs. A word of caution is in order, however: If you create too many
threads, you can actually degrade the performance of your program rather
than enhance it.
• Remember, some overhead is associated with context switching. If you
create too many threads, more CPU time will be spent changing contexts
than executing your program!
Multithreading:
41

END

You might also like