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

MULTI-THREADING

The document provides an extensive overview of multithreading in Java, explaining concepts such as multitasking types, thread definition methods, thread lifecycle, and thread synchronization. It also covers thread priorities, methods to manage thread execution, inter-thread communication, and potential issues like deadlock. Key points include the importance of the Thread class and Runnable interface, as well as synchronization techniques to ensure consistency in multi-threaded applications.

Uploaded by

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

MULTI-THREADING

The document provides an extensive overview of multithreading in Java, explaining concepts such as multitasking types, thread definition methods, thread lifecycle, and thread synchronization. It also covers thread priorities, methods to manage thread execution, inter-thread communication, and potential issues like deadlock. Key points include the importance of the Thread class and Runnable interface, as well as synchronization techniques to ensure consistency in multi-threaded applications.

Uploaded by

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

******CH-9 MULTI-THREADING [durga volume2 [41- 83 -106] [hk 2 volume page

40]***************************

*** INTRODUCTION:
-----------------

**WHAT IS MULTI-TASKING ?
ANS: executing several tasks simultaneously.

** MULTI TASKING TYPES:


1 process based
2 Thread based

1 Process Based:- executing several tasks simultaneously where each task is


seprate indepedent process.
----------------
ex: typing, listening, downloding,

2 Thread Based:- executing several tasks simultaneously where each task is


seprate indepedent part of same program.
and each part is called a "Thread".

ex: its best sutaible for programatic level.


and its easy in java, becouse java provide in built support for multithreading
through a API [Thread, Runnable, ThreadGroup,ThreadLocal, etc.]

ex: application areas:


----------------------
1 multi media area
2 animation
3 video games
4 web and application servers

**Note:- The main objective of multithreading is to improve performance of system


by reducing response time.

** HOW MANY WAYS , WE CAN DEFINE THREADS?


ANS:

we can define thread in 2 ways


1 by extending Thread class
2 by implementing Runnable interface.

**Imp-Note:
-----------

CASE 1: if multiple threads waiting to execute then which thread will execute
decided by " Thread Schedular " which is part of JVM.

CASE 2: Diff bw case of t.start() and t.run() :


> t.start()-> a new thread will be created which run run() mehtod.
but
> in case of t.run() no new thread created and run() executed just like a normal
method by main thread.

CASE 3: importancy of thread class start() method.


>for every thread the req activities like
ex: 1 registring thread with thread sheduler and call run() method-take care by
start() method of Thread.

Note:- without Thread class start() method , there is no chance of starting a new
thread in java, due to this start() is considerd as heart of multithreading.

CASE 4: if we are not overriding run() method:


> then thread class run() method will be executed which has empty impl so we not
get any op.

Note:- highly recommended to override run() .else we dont go for multithreading.

CASE 5: Overloading of run() method.


> we can overload but thread class start() method always invokes no argument run()
and to call other overload method we have to call exeplicitally. and it will
executed just like normal mehtod.

CASE 6: overriding of start() method:


> if we override start() method then our start() method will be executed just like
a normal mehtod call and no new thread will be started.

ex:- entire op produced by only main thread.

Note:- it is never recommended to override start() method.

CASE 7: Life cycle of Thread:


ex:
t.start() if TS allocates CPU if run()
method copmlete
new/born --------------> Ready/Runnable ---------------------------- Running
------------------------------- dead

1 once we create a Thread obj-> then its called new state or born state.

2 if call start() method -> thread will be entered into Ready/Runnable.

3 if sheduler allocates CPU -> then Thread will be entered into running state.

4 once run method completes -> then thread will be intered into dead state.
CASE 9:
>after starting a thread we are not allowed to restart same thread once again. else
get IllegalTreadStateException.

**** DEFINING A THREAD BY IMPLEMENTING RUNNABLE INTERFACE:


----------------------------------------------------------

we can define thread even by impl runnable interface also.


runnable present in java.lang package and it contains only one method run().

ex: 1 => Runnable 2 => Runnable


| |
Thread MyRunnable
|
MyThread

Note:- we can not expect exact op.

** CASE STUDY:
---------------

MyRunnable r = new MyRunnable();

Thread t1 = new Thread();


Thread t2 = new Thread(r);

CASE 1 : t1.start()
-------------------
a new thread will be created , which execute Thread class run() method.
so here op comes only from main thread not child thread.

CASE 2 : t1.run()
-------------------
new thread will not created , Thread class run() method executed like normal
method call.
so here op comes only from main thread not child thread.

CASE 3 : t2.start()
-------------------
a new thread will be created , which execute MyRunnable class run() method.
so here op comes from both main thread and child thread.

CASE 4 : t2.run()
-------------------
new thread will not be created , MyRunnable class run() method.just like normal
method.
so here op comes from both main thread and child thread.

CASE 5 : r.start()
-------------------
CE:- start() method is not in MyRunnable.

CASE 6 : r.run()
-------------------
new thread will not be created , MyRunnable class run() method.just like normal
method.
so here op comes from both main thread and child thread.

Note

Q-when new thread will be and executed MyRunnable run() method?


ans:- t2.start();

Q-when executed MyRunnable run() method?


ans:-t2.start();
t2.run();
r.run();

Q which is best approach to define a thread ?


ans- second approach is best - impl Runnable interface , we can extend some other
class also. so its recommended.

** THREAD CLASS CONSTRUCTORS:


------------------------------

1 Thread t = new Thread();

2 Thread t = new Thread(Runnable r);


3 Thread t = new Thread(String name);

4 Thread t = new Thread(Runnable r, String name);

5 Thread t = new Thread(ThreadGroup, Runnable r);

6 Thread t = new Thread(ThreadGroup, String name);

7 Thread t = new Thread(ThreadGroup, Runnable r, String name);

8 Thread t = new Thread(ThreadGroup, Runnable r, String name, long stackSize);

** GETTING AND SETTING NAME OF A THREAD:


----------------------------------------

every thread in java has some name , it may provided by explicitally by programmer
or jvm.

** thread class define method are:-

1 public final string getName();


2 public final void setName();

ex:

sop(Thread.currentThread.getName()); // to get main thread name

sop(t.getName()); // to get thread name

Thread.currentThread().setName("Bhaskar Thread");

Q-how we can get current executing thread obj ref ?


ans: Thread.currentThread();

** THREAD PRIORITIES:
---------------------
>every thread in java has some prority , it may default generated by JVM or
explicitally provided by programmer.

> thread range is 1 to 10 , not 0-10, where 1 is the least priority and 10 is
high priority.

Note:- thread class define following constant to represent ....


1 Thread.MIN_PRIORITY // 1
2 Thread.HIGH_PRIORITY // 10
3 Thread.NORM_PRIORITY // 5

> Thread Sheduler use these priorty while allocating CPU.


> highest proirty will get chance to 1st execution.

Note: if 2 threads having same priority then we can not expect execution order.
Q-how to get thread priority
ans: 2 methods are

1 public final int getPriority();


2 public final void setPriority(int newPriority); // only allow value 1 to 10.

** DEFAULT PRIORITY:
---------------------
> allowed only for main method thread is 5. but for all remaining threads default
prirority will be inheriting from parent to child.
means whatever parent has priority same will be for child also.

** METHODS TO PREVENT A THREAD FROM EXECUTION:


----------------------------------------------

1 yield()
2 join()
3 sleep()

1 yield():- to pause current executing thread for giving chance to remaing waiting
threads of same priority.
----------
1= but if all waiting thread have low priority
or
if there is no waiting thread -->then same thread will be continue.

2=>if several waiting threads of same priority then we can not expect order.

mehtod: public static native void yield()

Note:- write yield method inside own for look block.

for(int i=1; i<6; i++) {


Thread.yield(); // now it will stop this and first give chance
to other thread.
System.out.println("Main"+i);
}

DIAG:
________thread.yield()[Runable <= running back]
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead
2 join(): use if a thread want to wait until completing other thread .
---------

its mehtods:

1 public final void join() throws InterruptedException

2 public final void join(long ms) throws InterruptedException

3 public final void join(long ms, int ns) throws InterruptedException

DIAG:

_________[waiting state]_________________
| |
|1- if t1 complete or |1-t2.join()
|2- if time expires or |2-t2.join(1000)
|3- if waiting got interruptted |3-t2.join(1000,100)
| |
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead

Note:- every join method throws InterruptedException, which is checked exception.


so compulsory we should handle either by try catch or by throws kw.

** Imp note:- if main td calls join on child td , and child td calls join on main
td obj then both td will wait for each other forever
and program will be hanged.

3 sleep() :
-----------
if a thread do not want to perform any operation for a particular amount of time
then use sleep().

2 public final void sleep(long ms) throws InterruptedException


3 public final void sleep(long ms, int ns) throws InterruptedException

_________[waiting state]_________________
| |
| |
|1- if time expires or |1-t2.join(1000)
|2- if waiting got interruptted |2-t2.join(1000,100)
| |
| |
new/born ----> Ready/Runnable ------------------------> Running
------------------dead

**INTERRUPTING A THREAD ?
-------------------------
if a thread can interrupt a sleeping or waiting thread by using interrupt() method
of thread class.
ex : public void interrupt();

** COMPARISION OF YIELD , JOIN , SLEEP() METHOD:


-----------------------------------------------

Priority yeild() join()


sleep()
-----------------------------------------------------------------------------------
--------------------------------------------
1 purpose | To pause current executing td for | if a thread wants to wait
util | if a thread do not want to perform
| giving chance to remaing waiting | completing some other
thread. | any operation for a perticular amount
| thread of same priority. | of
time.
-----------------------------------------------------------------------------------
---------------------------------------------
2 is it static?| yes | no
| yes
-----------------------------------------------------------------------------
--------------------------------------------------
3 is it final? | no | yes
| no
-----------------------------------------------------------------------------------
--------------------------------------------
4 is it overloaded| no | yes
| yes
-----------------------------------------------------------------------------------
--------------------------------------------
5 is it throws InterruptedException| no | yes
|yes
-----------------------------------------------------------------------------------
--------------------------------------------
6 is it native method | yes | no
| sleep(long ms)=native
| sleep(long ms,
int ns) non native
===================================================================================
============================================

******* SYNCRONIZATION: [used to solve consistancy prog, it allowed one thread


at a time on methods or block]
==========================
>its kw applicable for method and blocks but not for classes and vars.
> if a method declare as syncronized then at a time only one thread allowed to
execute that method or block on given object.
> it used to resolve inconsistancy problums.
> disadavantage of this is , it increase waiting time.

> if there is no special requirement then never reccommneded to use it.


> internally syncronization concept is impl by using lock concept.
every object in java has a unique lock. but it comes in picture after using
syncronized

Note:- if a thread want to execute any syncronized method on given obj then
first it has to get lock of that object.
once a thread got lock then its allowed to execute any syncronized method on
that object.
and after execution completion automatically thread release lock.

Note:- remaining thread are not allowed execute syncronized method simultancialy
but remaining threads allowed to execute non syncronized method simultancially.

[Note:- lock concept is impl based on object but not based on method]

IMP NOTE:
1 if multiple threads are operating on multiple objects then there is no impact of
syncronization
2 if multiple threads are operating on same objects then there is require
syncronization.
Q** class level lock:-
--------------------
1- every class in java has a unique lock. if a thread wants to execute a static
syncronized mehtod then it req class level lock.
2 once a thread got class level lock then it is allow to execute any static
syncronized mehtod .
3 class level lock and object level lock both are diff and there is no
relationship bw these two.

Q** Syncronized Block :


-----------------------
> if very few lines of code required syncronized then we have to enclose those few
lines of code with in syncronized block ,
but not entire method sycronized.
> main advantage of it that it reduces waiting time of thread and improves
performance of system.

> to get lock of current obj we declare sycronized block as


Syncronized(this){}
if thread got lock of current obj then only it allow to execute this block.

> to get class level lock we have to declare syncronized block , we can pass obj
ref or .class file and we can not pass primitive values as argument. because lock
concept is depend only for object and class but not for primitives.

** Note:- Read imp quetion form durga volume 2 page 69.

** INTER THREAD COMMUNICATION [ WAIT() , NOTIFY(), NOTIFYALL() ]


----------------------------------------------------------------

> Two thread can communicate with each other by using wait(), notify() , and
notifyAll() mehtods.
> Thread which is required updation it has to call wait() mehtod on the req obj
then immediately the thread will entered into waiting state.
the thread which is performing updation of object , its responsible to give
notification by calling notify() method.
> after getting notification the waiting Thread will get updations.

> wait, notify, and notifyAll methods are avaible in object class but not in thread
class because thread can call these method on any common object.
ex:
1- current thread should has lock of that object
2- current thread should be in syncronized area. so we can call wait(),notify(),
notifyAll() methods only from syncronized area else get RE.

> once a thread calls wait() method on given object , first it release the lock of
that object immediataly and entered into waiting state.
except these[wait, notify, and notifyAll methods] there is no other place [method]
the lock release happen.
Q-in how many method can release lock ?
ans:-3 - wait, notify, notifyAll

Q-see all method definition 71 ?

Q-** what is Producer consumer problum ? [ans-72]


----------------------------------------

** notify Vs notifyAll():
-------------------------
> we can use notify() to give notification for only one thread
and if multiple threads are waiting then one thread will get chance and remaining
threads has to wait for further notification.
but which thread will be notify(inform) we can not expect exactly its depends on
JVM.

> we can use notifyAll() method to give notification for all waiting threads. All
threads will be notified and will be executed one by one ,
because they required lock.

Q-which following stmt are true ?


---------------------------------

Q1 Once a thread call wait on any object, immediataly it will entered into waiting
state without releasing the lock ?
ans: No

Q2 Once a thread call wait on any object , it reduce the lock of that object but
may not immediately ?
ans: No

Q3 Once a thread call wait on any object , it immediataly release all locks
whatever it has and entered into waiting state ?
ans: No

Q4 Once a thread call wait on any object , it immediataly release lock of that
perticular object and entered into waiting state ?
ans: YES

Q5 Once a thread call notify() on any object , it immediataly release lock of that
object?
ans: NO

Q5 Once a thread call notify() on any object , it release lock of that object ,
but not immediataly ?
ans: yes
** DEAD-LOCK :-
----------------
if 2 threads are waiting for each other forever (without end), this situation
(infinite waiting) is called dead lock.
Note:- there are no resoluation for dead lock but several prevention [avoidance
technics ] are possible.

Note:- Syncronized kw is the cause for deadlock, so while using it take care.

imp-note:- if we remove syncronized keyword some where then we will not get
DeadLock.
so syncronized kw only one reason for DeadLock due to this we have to handling
carefully.

** Deamon -Threads:-
--------------------
Def:-threads which are executing in background are called daemon threads.
the main objective of daemon threads is to provide support for non daemon
threads like main thread.

ex:- Garbage collector:- when our program runs with low memory , then jvm will
execute GC to provide free memory so that main thread can continue its execution.

> we can check thread is daemon or not using-isDaemon() of thread class.


public final boolean isDaemon();

> we can change daemon natur of a thread by using setDaemon() method but befor
starting thread only but not after starting.

> Note:- Main thread is always non daemon and for remaining threads daemon natur
will be inheriting from parent to child ,if parent is daemon child also daemon.

> whenver last non daemon thread terminates automatically all daemon threads will
be terminated.

**Lazy thread:-
---------------
if main thread is non daemon and child thread is daemon and whenver main thread
terminates automatically child thread will be terminated.

** DEADLOCK VS STARVATION :-
----------------------------
> a long waiting of a thread which never ends is called deadlock.
> a long waiting of a thread which ends at certain point is called starvation.
Q- HOW TO KILL A THREAD IN THE MIDDLE OF THE LINE ?
---------------------------------------------------
we can call stop() method to stop a thread in the middle then it will entered into
dead state immediatally.
public final void stop();

Note:- but stop method has deprecated and not recommended to use.

** SUSPEND AND RESUME METHODS:-


-------------------------------
> suspend():-a thread can suspend another thread by using suspend() method then
that thread will be paused temporarily.
> resume():- a thread can resume a suspended thread by using resume() method then
suspended thread will be continue its execution.

1 public final void suspend();


2 pubic final void resume();
Note:- both method are deprecated and not recommended to use.

** WHAT IS RACE CONDITION ?


---------------------------
> executing multiple thread simultaneously and causing data inconsistancy problum
is called race condition.
we can resolve Race condition by using syncronized kw.

** ThreadGroup:-
----------------
> based on functionality we can group threads as a single unit which is nothing but
ThreadGroup.
> ThreadGroup provides a way to common operations for all threads belongs to a
perticular group.

> we can create a thread group by using the following constructorss


ex: ThreadGroup g = new ThreadGroup(String gname);

> we can attach a thread to the threadGroup by using const..


ex: Thread t = new Thread(ThreadGroup g, String name);

Q- ThreadLocal ?
----------------
ans:- we can use threadLocal to define local resources which are required for a
perticular Thread like DBConnecitons, CounterVars.
we use ThreadLocal to define Thread scope like Servlet scope (page, request,
session, application).

Q- GreenThread ?
----------------
ans:- java multithreading concept is implementing by using following 2 methods.

1 GreenThread Model
2 Native OS Model

Note:-
1 GreenThread:-the threads which are managed completely by JVM wihtout taking
support for underlying OS, called Green Threads.
2 Native OS :- the threads which are managed with the help of underlying OS .

Note:- windows based OS provide support for native OS model.


and GreenThread model is deprecated and not recommended to use.

VVIMP:
Q-Life Cycle of a thread ? [ans- see video and pictur in 80 page.]

Q- what is diff bw extends Thread and implement Runnable ? and which is better ?
ans:
1 extends Thread:- useful to override public void run() of Thread class.
2 implement Runnable:-useful to implement public void run() of Runnable interface.

if we implement Runnable then there is a chance to extend another class. but if we


extends thread class , then no chance of extend another class.

Q- HOW WE CAN STOP A THREAD WHICH IS RUNNING ?


STEP1:- declare a boolean type var and store false
boolean stop=false;
STEP2:- if var become true return from run()
if(stop)
return;
STEP3:- whenever to stop the thread store true into var
System.in.read(); // press enter
obj.stop=true;

Q *** Note:- read all given q on thread and give ans for interview -vedio 14 page
81]

================= MULTITHREADING
ENHANCEMENT================================================

1 ThreadGroup
2 ThreadLocal
3 java.util.concurrent.locks package
Lock(I)
ReentrantLock(C)
4 Thread Pools
5 Callable and Future
----------------------------------

1 ThreadGroup:-
----------------
> based on functionality we can group threads as a single unit which is nothing but
ThreadGroup.
> ThreadGroup represent a set of Threat . it also contains other subthreadGroups.
> ThreadGroup provides a way to common operations for all threads belongs to a
perticular group.
> ThreadGroup class present in java.lang package its direct child of object.

Note:- the main advantage of maintaining thread in form of group is , we can


perform common opreration for all Thread belongs to a perticular group.

ex:- 1 stop all consumer threads


2 suspend all producer threads

** CONSTRUCTOR:-
----------------

1 ThreadGroup g = new ThreadGroup(String gname);


=> create a new ThreadGroup and the parent of this new Group is the ThreadGroup of
currentaly running thread.

2 ThreadGroup g = new ThreadGroup(ThreadGroup g, String gname);


=> create a new ThreadGroup and parent of this new ThreadGroup is the specified
ThreadGroup.

Note:-
1- in java, every thread belongs to some group.
2 every ThreadGroup is the child group of System Group either directally or
indirectally. so System Group acts as a root for all ThreadGroup in java.
3 System ThreadGroup represents System Level Threads Like ReferenceHandler,
SignalDispatcher, Finalizer, AttachListener.

Q- IMP METHOD OF THREADGROUP CLASS:


-----------------------------------
1 String getName(); // return name of ThreadGroup
2 intgetMaxPriority() // return max priority of ThreadGroup

3 void setMaxPriority();
>to set max priority of the ThreadGroup
>default max priority is 10
> threads in the ThreadGroup that already have higher priority , not effected
but newly added threads this applicable.

4 ThreadGroupgetParent(); // return parent group of current ThreadGroup

5 void list(); // prints info about ThreadGroup to the console.


6 int activeCount(); // return number of active threads present in ThreadGroup

7 int activeGroupCount() // return number of active threadGroup present in current


ThreadGroup

8 int enumerate(Thread[] t); // to copy all active threads of this group into
provided thread array. and subthreadgroup also included.

9 int enumerate(Thread[] t); // to copy all active subthreadgroup into threadgroup


array.

10 boolean isDaemon();

11 void setDaemon(boolean b);

12 void interrupted(); // to interrupted all threads present in thread group.

13 void destroy() ; // to destroy threadgruop and its subthreadgruop


----------------------------------------------------------------------

2 ThreadLocal:
==============
>thread local provide local vars.
> maintains values for thread basis.
> each ThreadLocal obj maintain a seprate value like userID, transactionId for each
thread that access that object.
> thread can access its local value, can manipulate its value and even can remove
its value.

vvi
Q- in real time where we use this ThreadLocal ?
ans:- see ans page 89

Note:-
>ThreadLocal can be associated with scope.
>all code which is executed by thread has access to correspondence ThreadLocal
vars.
>a thread can access only its own local vars not other threads vars.
>once thread entered into Dead state all local vars are by default eligible for GC.

Q- See the constructor and method of ThreadLocal? page 90

Q- ThreadLocal Vs InheritanceThreadLocal ?
InheritanceThreadLocal
method and constructors
--------------------------------------------------------------------------------
3 JAVA.UTIL.CONCURRENT.LOCKS PACKAGE:
-----------------------------------------

problum with tradition syncronized keyword:


-------------------------------------------
1 if a thread releases lock then which waiting thread will get that lock , we not
have control on this.

2 we can not specify maximum waiting time for a thread to get lock so it will until
getting lock,
3 not flexibilty with try
4 no API to list all waiting threads for a lock.
5 the syncronized kw is compulsory to define within a method

** to overcome these prob sun introduced java.util.concurrent.locks package in


1.5 version

Lock(I):
--------
>a lock Object is similar to implicit Lock acquired by thread to execute
syncronized method or block.
>lock implementations provide more extensive operations then tradition locks.

** IMP METHODOS LOCK INTERFACE: [VVIMP-- READ FROM 93 PAGE]


------------------------------

4 THREAD POOLS:
=================
its pool of already created threads ready to do our job.
> java 1.5 v introduced Thread Pool framwork to impl thread pools.
> Thread Pool framwork is also known as executor framwork.

we can create pool as


ex: executorservice ser = executor.newFixedThreadPool(3); // our choice

we can submit a runnable job by using submit() method.


ser.submit();

we can shutdown executorservices by using shutdown()


ser.shutdown();

** Note:- we use ThreadPool concept to impl servers [web / app server]

-----------------------------------------------------------------------
5 CALLABLE AND FUTURE:
======================
> if a thread req to return some result after execution then use callable
> callable interface contains only one method
public Object call() throws Exception.

> if we submit a callable object to executor then framwork return an Object of type
java.util.concurrent.Future

> the future Object can be used to retrive the result from Callable job.

** VVIMP NOTE:- READ AND WATCH ALL IMP Q GIVEN AT PAGE 103
------------------------------------------------------------

You might also like