0% found this document useful (0 votes)
12 views44 pages

Oops U4

This document covers multithreading and generic programming in Java, detailing the concepts of threads, their life cycle, synchronization, and the creation of threads using both the Thread class and Runnable interface. It also discusses generic methods and classes, including their benefits, restrictions, and limitations. Key topics include thread priorities, inter-thread communication, and the use of locks for synchronization.
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)
12 views44 pages

Oops U4

This document covers multithreading and generic programming in Java, detailing the concepts of threads, their life cycle, synchronization, and the creation of threads using both the Thread class and Runnable interface. It also discusses generic methods and classes, including their benefits, restrictions, and limitations. Key topics include thread priorities, inter-thread communication, and the use of locks for synchronization.
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/ 44

UNIT-IV

MULTITHREADING AND GENERIC PROGRAMMING


Multithreading
P

• Multithreading in java is a process of


executing multiple threads
simultaneously.
• A thread is a lightweight sub-process,
TT
the smallest unit of processing.
T
• Threads use a shared memory area.
Differences between Multithreading and
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.
- Process-based Multitasking (Multiprocessing)
Each process has an address in memory.
- Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread Life Cycle
Thread Life Cycle
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread Priorities
• Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
• 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).
Creating Threads
• There are two ways to create a thread:
• By extending Thread class.
• By implementing Runnable interface.
Thread class
• Thread class provide constructors and methods to create and perform
operations on a thread.
• Thread class extends Object class and implements Runnable interface.
• Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Thread methods
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread. JVM calls the run()
method on the thread.
• public void sleep(long milliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of
milliseconds.
• public void join(): waits for a thread to die.
• public void join(long milliseconds): waits for a thread to die for the
specified milliseconds.
• public int getPriority(): returns the priority of the thread.
Thread methods
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing
thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
Thread methods
• public void suspend(): is used to suspend the thread.
• public void resume(): is used to resume the suspended thread.
• public void stop(): is used to stop the thread.
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user
thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been
interrupted.
Runnable interface
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
• Runnable interface have only one method named run().
• public void run(): is used to perform action for a thread.
Runnable interface
Starting a thread:
• start() method of Thread class is used to start a newly created thread. It
performs following tasks:
- A new thread starts(with new callstack).
- The thread moves from New state to the Runnable state.
- When the thread gets a chance to execute, its target run() method will
run.
Java Thread Example by extending
Thread class
class Multi extends Thread Output:
{
public void run() //RUNNING thread is running...
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(); //NEW
t1.start(); //RUNNABLE
}
}
Java Thread Example by implementing
Runnable interface
class Multi3 implements Runnable Output:
{
public void run() thread is running...
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Synchronizing Threads
• Synchronization in java is the capability to control the access of
multiple threads to any shared resource.
• Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
• The synchronization is mainly used to
- To prevent thread interference.
- To prevent consistency problem.
Synchronizing Threads
• There are two types of thread synchronization mutual exclusive and
inter-thread communication.
• Mutual Exclusive
• Synchronized method.
• Synchronized block.
• static synchronization.
• Inter-thread communication
Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another
while sharing data.
• This can be done by three ways in Java:
- by synchronized method
- by synchronized block
- by static synchronization
Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or
monitor.
• Every object has an 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.
Mutual Exclusive - By synchronized
method
• If you declare any method as synchronized, it is known as
synchronized method.
• Synchronized method is used to lock an object for any shared
resource.
• When a thread invokes a synchronized method, it automatically
acquires the lock for that object and releases it when the thread
completes its task.
Mutual Exclusive - By synchronized block
• Synchronized block can be used to perform synchronization on any
specific resource of the method.
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression)
{
//code block
}
Static synchronization
• If you make any static method
as synchronized, the lock will be
on the class not on object.
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()
Inter thread communication
• Threads enter to acquire lock.
• Lock is acquired by on thread.
• Now thread goes to waiting state if you
call wait() method on the object.
Otherwise it releases the lock and exits.
• If you call notify() or notifyAll()
method, thread moves to the notified
state (runnable state).
• Now thread is available to acquire lock.
Inter thread communication
• After completion of the task, thread
releases the lock and exits the
monitor state of the object.
• wait(), notify() and notifyAll()
methods are defined in Object class
not Thread class because they are
related to lock and object has a lock.
Difference between wait and sleep
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
should be notified by notify() or after the specified amount of time,
notifyAll() methods sleep is completed.
Daemon threads
• Daemon thread in Java is a service provider thread that provides
services to the user thread.
• Its life depend on the mercy of user threads i.e. when all the user
threads dies, JVM terminates this thread automatically.
• It provides services to user threads for background supporting tasks. It
has no role in life than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.
Thread groups
• A ThreadGroup represents a set of threads.
• A thread group can also include the other thread group.
• The thread group creates 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 it cannot access the information about its thread group's parent
thread group or any other thread groups.
• Java thread group is implemented by java.lang.ThreadGroup class.
Thread groups
Constructor Description
ThreadGroup(String name) creates a thread group with given
name.
ThreadGroup(ThreadGroup creates a thread group with given
parent, String name) parent group and name.
Thread groups
Method Description
checkAccess() This method determines if the currently running
thread has permission to modify the thread group.
activeCount() This method returns an estimate of the number of
active threads in the thread group and its subgroups.
activeGroupCount() This method returns an estimate of the number of
active groups in the thread group and its subgroups.
destroy() This method destroys the thread group and all of its
subgroups.
Thread groups
Method Description
enumerate(Thread[] list) This method copies into the specified array every
active thread in the thread group and its subgroups.
getMaxPriority() This method returns the maximum priority of the
thread group.
getName() This method returns the name of the thread group.
getParent() This method returns the parent of the thread group.
Thread groups
Method Description
interrupt() This method interrupts all threads in the thread group.
isDaemon() This method tests if the thread group is a daemon
thread group.
setDaemon(boolean d) This method changes the daemon status of the thread
group.
isDestroyed() This method tests if this thread group has been
destroyed.
Generic programming
• Java Generic methods and generic classes enable programmers to
specify, with a single method declaration, a set of related methods, or
with a single class declaration, a set of related types, respectively.
• Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time.
Generic Methods
• A single generic method declaration that can be called with arguments
of different types.
• Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately.
Generic Methods
• All generic method declarations have a type parameter section delimited
by angle brackets (< and >) that precedes the method's return type ( < E >
in the next example).
• Each type parameter section contains one or more type parameters
separated by commas.
• The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments.
• A generic method's body is declared like that of any other method.
Bounded Type Parameters
• Restrict the kinds of types that are allowed to be passed to a type
parameter.
• For example, a method that operates on numbers might only want to
accept instances of Number or its subclasses.
• This is what bounded type parameters are for.
• To declare a bounded type parameter, list the type parameter's name,
followed by the extends keyword, followed by its upper bound.
Generic Classes
• A generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section.
• As with generic methods, the type parameter section of a generic class
can have one or more type parameters separated by commas.
• These classes are known as parameterized classes or parameterized
types because they accept one or more parameters.
Restrictions and limitations
• Cannot Instantiate Generic Types with Primitive Types
• Cannot Create Instances of Type Parameters
• Cannot Declare Static Fields Whose Types are Type Parameters
• Cannot Create Arrays of Parameterized Types
• Cannot Create, Catch, or Throw Objects of Parameterized Types
Cannot Instantiate Generic Types with
Primitive Types
public class GenericsTester class Box<T>
{ {
public static void main(String[] args) private T t;
{ public void add(T t)
Box<Integer> integerBox = new Box<Integer>();
//Box<int> stringBox = new Box<int>(); {
integerBox.add(new Integer(10)); this.t = t;
printBox(integerBox); }
} public T get()
private static void printBox(Box box) {
{ return t;
System.out.println("Value: " + box.get()); }
} }
}
Cannot Create Instances of Type
Parameters
class Gen<T>
{
T ob;
Gen()
{
ob = new T();
}
}
Cannot Declare Static Fields Whose Types
are Type Parameters
class Wrong<T>
{
static T ob;
static T getob()
{
return ob;
}
static void showob()
{
System.out.println(ob);
}
}
Cannot Create Arrays of Parameterized
Types
class MyClass<T extends Number> public class Main
{ {
T ob; public static void main(String args[])
T vals[]; {
MyClass(T o, T[] nums) Integer n[] = { 1 };
{ MyClass<Integer> iOb = new
ob = o; MyClass<Integer>(50, n);
vals = nums; MyClass<?> gens[] = new MyClass<?>[10];
} }
} }
Cannot Create, Catch, or Throw Objects of
Parameterized Types
void execute(List<J> jobs)
//The generic class Box<T> not
{
subclass java.lang.Throwable
try
class Box<T> extends Exception {} {
for (J job : jobs)
//The generic class Box<T> not {}
subclass java.lang.Throwable // compile-time error
class Box1<T> extends Throwable {} }
catch (T e)
{}
}
Thank you

You might also like