0% found this document useful (0 votes)
21 views43 pages

Unit 4 - LMS

Uploaded by

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

Unit 4 - LMS

Uploaded by

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

Unit 4

MULTITHREADING AND GENERIC PROGRAMMING

Differences between multi-threading and multitasking, thread life cycle, creating threads,
synchronizing threads, Inter-thread communication, daemon threads, thread groups. Generic
Programming – Generic classes – generic methods – Bounded Types – Restrictions and Limitations.
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between multi-threading and
multitasking
Differences between MultiTasking and
Multithreading
1.The basic difference between multitasking and multithreading is that
in multitasking, the system allows executing multiple programs and tasks
at the same time, whereas, in multithreading, the system executes
multiple threads of the same or different processes at the same time.
2.In multitasking CPU has to switch between multiple programs so that it
appears that multiple programs are running simultaneously. On other
hands, in multithreading CPU has to switch between multiple threads to
make it appear that all threads are running simultaneously.
3.Multitasking allocates separate memory and resources for each
process/program whereas, in multithreading threads belonging to the
same process shares the same memory and resources as that of the
process.
Multitasking and Multithreading
Examples of multitasking and multithreading
• MultiTasking is sharing of computer resources among number of
processes or execution of different processes at the same time
like working on MSOffice while VLC player is running whereas

• MultiThreading is execution of number of different tasks within a


same process like in MSWord while you are writing the autocorrection
is performed simultaneously.
Lifecycle of Thread
A thread can be in any one of the following states at any instant:
• New
• Runnable
• Blocked
• Waiting
• Timed waiting
• Terminated
Creating Threads in Java
• Java allows us to create threads in two ways :
1.Extending the Thread Class
2.Implementing the Runnable Interface
Multithreading
• Java’s multithreading features work in both types of systems.
• In a single-core system, concurrently executing threads share the
CPU, with each thread receiving a slice of CPU time.
• Therefore, in a single-core system, two or more threads do not
actuallyr un at the same time, but idle CPU time is utilized.
• In multi-core systems, it is possible for two or more threads to
execute simultaneously. This improves the program efficiency and
also increase the speed of certain operations.
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.
• 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
Thread Priorities
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value


of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10
Context Switch among threads in Java
• 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 higher-priority thread. A higher priority
thread runs when it wants to. This is called preemptive multitasking.
Synchronization among threads
• Because multithreading introduces an asynchronous behavior to your
programs, there must be a way for you to enforce synchronicity when
you need it.
• 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 age-old model of interprocess synchronization: the
monitor.
• Each object has its own implicit monitor that is automatically entered
when one of the object’s synchronized methods is called.
Synchronization among threads (Cont..)
• 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.
Thread Class Methods
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.
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.
• 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.
Synchronizing Threads
• Synchronization in Java is the capability to control the access of
multiple threads to any shared resource.
• The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.
Thread Synchronization

• There are two types of thread synchronization mutual


exclusive and inter-thread communication.
1.Mutual Exclusive
1. Synchronized method.
2.Synchronized block.
3.Static synchronization.
2.Cooperation (Inter-thread communication in java)
Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or
monitor.
• Every object has a lock associated with it.
• By convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
Inter-thread communication
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• 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
Inter-thread communication
• It provides an efficient way through which more than one thread
communicate with each other by reducing CPU idle time. CPU idle
time is a process in which CPU cycles are not wasted.
• When more than one threads are executing simultaneously,
sometimes they need to communicate with each other by exchanging
information with each other. A thread exchanges information before
or after it changes its state.
Inter-thread communication
• There are several situations where communication between threads
is important.
• For example, suppose that there are two threads A and B. Thread B
uses data produced by Thread A and performs its task.

• If Thread B waits for Thread A to produce data, it will waste many CPU
cycles.
• But if threads A and B communicate with each other when they have
completed their tasks, they do not have to wait and check each
other’s status every time.
How to achieve Inter-thread communication ?
• wait()
• notify()
• notifyAll()

• These methods can be called only from within a synchronized method


or synchronized block of code otherwise, an exception
named IllegalMonitorStateException is thrown.
wait()
• The wait() method causes current thread to release the lock and wait
until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has
elapsed.

Method Description

public final void wait()throws It waits until object is notified.


InterruptedException
public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
notify()
• The notify() method wakes up a single thread that is waiting on this
object's monitor.
• If more than one thread is waiting, this method will awake one of
them.
notifyAll()
• The notifyAll() method is used to wake up all threads that called
wait() method on the same object. The thread having the highest
priority will run first.
Differences between sleep and wait methods
wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Daemon Thread
• Daemon thread in Java are those thread which runs in background and mostly created by
JVM for performing background task like Garbage collection.

• Daemon threads executes at a low priority.

• Daemon threads are threads that run intermittently in the background as long as other
non-daemon threads are running.

• When all of the non-daemon threads complete, daemon threads terminates


automatically.

• Daemon threads are service providers for user threads running in the same process.
Thread Groups
• ThreadGroup creates a group of threads. It offers a convenient way to
manage groups of threads as a unit. This is particularly valuable in
situation in which you want to suspend and resume a number of
related threads.
• The thread group form a tree in which every thread group except the
initial thread group has a parent.
• A thread is allowed to access information about its own thread group
but not to access information about its thread group’s parent thread
group or any other thread group.
Thread Group

Constructor Description

ThreadGroup(String name) creates a thread group with given name.

ThreadGroup(ThreadGroup parent, String creates a thread group with a given parent


name) group and name.
Generics in Java
• Before generics, we can store any type of objects in the collection,
i.e., non-generic. Now generics force the java programmer to store a
specific type of objects.
• The Java Generics programming is introduced in J2SE 5 to deal with
type-safe objects. It makes the code stable by detecting the bugs at
compile time.
Advantage of Java Generics

1) Type-safety: We can hold only a single type of objects in


generics. It doesn’t allow to store other objects.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need
to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
Advantage of Java Generics
2) Type casting is not required: There is no need to
typecast the object.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Advantage of Java Generics
3.Compile-Time Checking: It is checked at compile time so
problem will not occur at runtime. The good programming
strategy says it is far better to handle the problem at compile
time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Generic Classes
• A class that can refer to any type is known as a generic class.
Here, we are using the T type parameter to create the generic
class of specific type.
• Let's see a simple example to create and use the generic class.
Creating a generic class:
class MyGen<T>{
T obj;
void add(T obj){this.obj=obj;}
T get(){return obj;}
}
Generic Methods
• Like the generic class, we can create a generic method that
can accept any type of arguments. Here, the scope of
arguments is limited to the method where it is declared.
Wildcard in Java Generics

• The ? (question mark) symbol represents the wildcard


element. It means any type. If we write <? extends
Number>
• It means any child class of Number, e.g., Integer, Float, and
double. Now we can call the method of Number class
through any child class object.

List<? extends Number>


List<? extends Number> is less restrictive
than List<Number>.
Bounded Types – Limits and Restrictions
1.Generics don't work with primitive types.
2.We cannot create an instance of a type parameter.
3.We cannot create, catch, or throw generic types.
4.We cannot declare static fields of a type parameter.

You might also like