SlideShare a Scribd company logo
Page 1 of 31
Class Notes on Multithreading (Week - 9)
Contents:- Basicsof multithreading,mainthread,threadlifecycle,creationof multiplethreads,threadsynchronization,
interthreadcommunication,deadlocksforthreads,suspending&resumingthreads.
Multithreading in Java
Multithreadingisaprocessof executingmultiple threadssimultaneously.Threadisbasicallya lightweight subprocess, a
smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than multiprocessing because threads share a common memory area. They don't allocate separate
memory area so save memory, and context-switching between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.
Multitasking
Multitaskingisaprocessof executingmultiple taskssimultaneously.We use multitaskingtoutilize the CPU.Multitasking
can be achievedbytwoways:
 Process-basedMultitasking(Multiprocessing)
 Thread-basedMultitasking(Multithreading)
1) Process-basedMultitasking(Multiprocessing)
 Each process has itsown addressinmemoryi.e.eachprocessallocates separate memoryarea.
 Processisheavyweight.
 Cost of communicationbetweenthe processes ishigh.
 Switchingfromone process toanotherrequire some time forsavingandloadingregisters,memorymaps,
updatinglistsetc.
2) Thread-basedMultitasking(Multithreading)
 Threadsshare the same addressspace.
 Threadis lightweight.
 Cost of communicationbetweenthe threadislow.
 Note:At leastone processisrequiredforeachthread.
What is Thread?
A threadisa lightweightsubprocess,asmallestunitof processing.Itisaseparate pathof execution.Itsharesthe
memoryareaof process.
As showninthe above figure, thread(t1,t2 and t3) isexecutedinside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Note:At a time onlyone thread isexecuted.
Page 2 of 31
Life cycle of a Thread (Thread States)
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non -
runnable andterminated.There isnorunningstate.Butforbetterunderstandingthe threads,we are explainingitin the
5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
1)New
The thread isinnewstate if youcreate an instance of Threadclass butbefore the invocationof start() method.
2)Runnable
The thread isinrunnable state afterinvocationof start() method,butthe threadschedulerhasnotselectedittobe the
runningthread.
3)Running
The thread isinrunningstate if the threadschedulerhasselectedit.
4)Non-Runnable(Blocked)
Thisis the state whenthe threadisstill alive,butiscurrentlynoteligibletorun.
5)Terminated
A threadisin terminatedordeadstate whenitsrun() methodexits.
How to create thread:
There are twowaysto create a thread:
1. By extendingThreadclass
2. By implementingRunnableinterface.
Thread class:
Threadclass provide constructorsandmethodstocreate and performoperationsonathread. Threadclassextends
Objectclassand implementsRunnable interface.
Page 3 of 31
CommonlyusedConstructorsofThread class:
 Thread()
 Thread(Stringname)
 Thread(Runnabler)
 Thread(Runnabler,Stringname)
CommonlyusedmethodsofThreadclass:
1. publicvoid run():is usedto performactionfora thread.
2. publicvoid start(): starts the executionof the thread.JVMcallsthe run() methodonthe thread.
3. publicvoid sleep(longmiliseconds): Causesthe currentlyexecutingthreadtosleep(temporarilycease
execution)forthe specifiednumberof milliseconds.
4. publicvoid join():waitsfora threadto die.
5. publicvoid join(longmiliseconds): waitsfora threadto die forthe specifiedmiliseconds.
6. publicint getPriority():returnsthe priorityof the thread.
7. publicint setPriority(intpriority): changesthe priorityof the thread.
8. publicString getName():returnsthe name of the thread.
9. publicvoid setName(Stringname): changesthe name of the thread.
10. publicThread currentThread(): returnsthe reference of currentlyexecutingthread.
11. publicint getId():returnsthe idof the thread.
12. publicThread.State getState():returnsthe state of the thread.
13. publicbooleanisAlive():testsif the threadisalive.
14. publicvoid yield():causesthe currentlyexecutingthreadobjecttotemporarilypause andallow otherthreadsto
execute.
15. publicvoid suspend():isusedtosuspendthe thread(depricated).
16. publicvoid resume():isusedtoresume the suspendedthread(depricated).
17. publicvoid stop():is usedtostop the thread(depricated).
18. publicbooleanisDaemon():testsif the threadis a daemonthread.
19. publicvoid setDaemon(booleanb):marksthe threadas daemonor userthread.
20. publicvoid interrupt():interruptsthe thread.
21. publicbooleanisInterrupted(): testsif the threadhasbeeninterrupted.
22. publicstatic booleaninterrupted(): testsif the currentthreadhasbeeninterrupted.
Runnableinterface:
The Runnable interface shouldbe implementedbyanyclasswhose instancesare intendedtobe executedbyathread.
Runnable interface have onlyone methodnamedrun().
1. publicvoid run():is usedto performactionfora thread.
Startinga thread:
start() methodof Threadclass isusedto start a newlycreatedthread.Itperformsfollowingtasks:
 A newthreadstarts(withnewcallstack).
 The thread movesfromNewstate tothe Runnable state.
 Whenthe threadgets a chance to execute,itstargetrun() methodwillrun.
Page 4 of 31
1)ByextendingThreadclass:
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...
Who makes yourclassobjectasthread object?
Thread class constructor allocatesanewthreadobject. Whenyoucreate objectof Multi class, yourclass constructoris
invoked (providedbyCompiler) from where Thread classconstructorisinvoked (bysuper() asfirststatement). Soyour
Multi class objectisthreadobjectnow.
2)Byimplementingthe Runnableinterface:
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...
If you are notextendingthe Threadclass, yourclassobjectwouldnot be treatedasa threadobject. Soyouneedto
explicitly create Threadclassobject. We are passingthe objectof yourclass thatimplementsRunnablesothatyourclass
run() methodmayexecute.
How to perform single task by multiple threads?
If you have to performsingle taskbymanythreads,have onlyone run() method. Forexample:
1. //Program of performing single task by multiple threads
2.
3. class Multi extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. public static void main(String args[]){
8. Multi t1=new Multi();
9. Multi t2=new Multi();
Page 5 of 31
10. Multi t3=new Multi();
11.
12. t1.start();
13. t2.start();
14. t3.start();
15. }
16. }
Output:task one
task one
task one
1. //Program of performing single task by multiple threads by implementing
Runnable.
2.
3. class Multi3 implements Runnable{
4. public void run(){
5. System.out.println("task one");
6. }
7.
8. public static void main(String args[]){
9. Thread t1 =new Thread(new Multi3());//passing annonymous obj of Multi3 class
10. Thread t2 =new Thread(new Multi3());
11.
12. t1.start();
13. t2.start();
14.
15. }
16. }
Output:task one
task one
Note: Each thread runin a separatecallstack.
Howto performmultipletasksbymultiple threads(multitasking inmultithreading)?
If you have to performmultipletasksbymultiple threads,have multiplerun() methods. Forexample:
1. // Program of performing two tasks by two threads.
2.
3. class Simple1 extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. }
8.
Page 6 of 31
9. class Simple2 extends Thread{
10. public void run(){
11. System.out.println("task two");
12. }
13. }
14.
15. class Test{
16. public static void main(String args[]){
17. Simple1 t1=new Simple1();
18. Simple2 t2=new Simple2();
19.
20. t1.start();
21. t2.start();
22. }
23. }
Output:task one
task two
Sameexampleas abovebyannonymousclassthat implementsRunnableinterface:
1. //Program of performing two tasks by two threads.
2.
3. class Test{
4. public static void main(String args[]){
5. Runnable r1=new Runnable(){
6. public void run(){
7. System.out.println("task one");
8. }
9. };
10.
11. Runnable r2=new Runnable(){
12. public void run(){
13. System.out.println("task two");
14. }
15. };
16.
17. Thread t1=new Thread(r1);
18. Thread t2=new Thread(r2);
19.
20. t1.start();
21. t2.start();
22. }
23. }
Output:task one
task two
The Thread Schedular:
 The thread scheduleristhe partof the JVMthat decideswhichthreadshouldrun.
 There isno guarantee thatwhichrunnable threadwill be chosentorunby the thread scheduler.
 Onlyone threadat a time canrun in a single process.
 The thread schedulermainlyusespreemptiveortime slicingschedulingtoschedule the threads.
Page 7 of 31
What is the differencebetweenpreemptiveschedulingandtimeslicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher
prioritytaskcomesintoexistence. Under time slicing, a task executes for a predefined slice of time and then reenters
the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other
factors.
Sleeping a thread (sleep() method):
The sleep() methodof Threadclassisusedto sleepathreadfor the specifiedtime.
Syntax of sleep() method:
The Thread classprovidestwomethodsforsleepingathread:
 publicstaticvoidsleep(longmiliseconds)throwsInterruptedException
 publicstaticvoidsleep(longmiliseconds,intnanos)throwsInterruptedException
1. // Program of sleep() method
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. Multi t1=new Multi();
12. Multi t2=new Multi();
13.
14. t1.start();
15. t2.start();
16. }
17. }
Output:1
1
2
2
3
3
4
4
5
5
As youknowwell thatat a time onlyone threadisexecuted.If yousleepathreadforthe specifiedtime, the thread
schedulerpicksupanotherthreadandso on.
Can we start a thread twice?
No.Afterstaringa thread,it can neverbe startedagain.If you doesso,an IllegalThreadStateExceptionisthrown.For
Example:
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
Page 8 of 31
6. Multi t1=new Multi();
7. t1.start();
8. t1.start();
9. }
10. }
Output:running
Exception in thread "main" java.lang.IllegalThreadStateException
What if we call run() method directly instead start() method?
 Each thread startsin a separate call stack.
 Invokingthe run() methodfrommainthread,the run() methodgoesontothe currentcall stackrather thanat
the beginningof anewcall stack.
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
Output:running...
1. //Problem if you direct call run() method
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e)
7. {System.out.println(e);}
8. System.out.println(i);
9. }
10. }
11. public static void main(String args[]){
12. Multi t1=new Multi();
13. Multi t2=new Multi();
14.
15. t1.run();
Page 9 of 31
16. t2.run();
17. }
18. }
Output:1
2
3
4
5
1
2
3
4
5
As youcan see inthe above programthat there isno context-switchingbecausehere t1andt2 will be treatedasnormal
objectnotthreadobject.
The join() method:
The join() methodwaitsforathreadto die.Inother words,itcausesthe currentlyrunningthreadstostopexecuting
until the threaditjoinswithcompletesitstask.
Syntax:
public void join()throws InterruptedException
public void join(long miliseconds)throws InterruptedException
1. // Example of join() method.
2.
3. classMulti extends Thread{
4. publicvoidrun(){
5. for(inti=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
10. }
11. }
12. publicstaticvoidmain(Stringargs[]){
13. Multi t1=new Multi();
14. Multi t2=new Multi();
15. Multi t3=new Multi();
16. t1.start();
17. try{
18. t1.join();
19. }catch(Exception e){System.out.println(e);}
20.
21. t2.start();
22. t3.start();
Page 10 of 31
23. }
24. }
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As youcan see inthe above example,when t1completesitstaskthent2 and t3 startsexecuting.
1. //Example of join(long miliseconds) method.
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
10. }
11. }
12. public static void main(String args[]){
13. Multi t1=new Multi();
14. Multi t2=new Multi();
15. Multi t3=new Multi();
16. t1.start();
17. try{
18. t1.join(1500);
19. }catch(Exception e){System.out.println(e);}
20.
21. t2.start();
22. t3.start();
23. }
24. }
Output:1
2
3
1
4
1
2
5
Page 11 of 31
2
3
3
4
4
5
5
In the above example,when t1iscompletesitstaskfor1500 milliseconds(3times) thent2andt3 starts executing.
getName(),setName(String)andgetId() method:
public String getName()
public void setName(String name)
public long getId()
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi6 t1=new Multi6();
7. Multi6 t2=new Multi6();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
ThecurrentThread()method:
The currentThread() methodreturnsareference tothe currentlyexecutingthread object.
Syntax:
publicstaticThreadcurrentThread()
Page 12 of 31
1. //Example of currentThread() method
2.
3. class Multi6 extends Thread{
4. public void run(){
5. System.out.println(Thread.currentThread().getName());
6. }
7. }
8. public static void main(String args[]){
9. Multi6 t1=new Multi6();
10. Multi6 t2=new Multi6();
11.
12. t1.start();
13. t2.start();
14. }
15. }
Output:Thread-0
Thread-1
Naming a thread:
The Thread classprovidesmethodstochange andgetthe name of a thread.
1. publicString getName():isusedto returnthe name of a thread.
2. publicvoid setName(Stringname): isusedto change the name of a thread.
Example of naming a thread:
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi6 t1=new Multi6();
7. Multi6 t2=new Multi6();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10.
11. t1.start();
12. t2.start();
13.
14. t1.setName("Sonoo Jaiswal");
15. System.out.println("After changing name of t1:"+t1.getName());
16. }
17. }
Output: Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Page 13 of 31
The currentThread() method:
The currentThread() methodreturnsareference tothe currentlyexecutingthreadobject.
Syntaxof currentThread()method:
 publicstatic Thread currentThread(): returnsthe reference of currentlyrunningthread.
Exampleof currentThread()method:
1. class Multi6 extends Thread{
2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. Multi6 t1=new Multi6();
8. Multi6 t2=new Multi6();
9.
10. t1.start();
11. t2.start();
12. }
13. }
Output:Thread-0
Thread-1
Priority of a Thread (Thread Priority):
Each thread hasa priority.Prioritiesare representedbyanumberbetween1and 10. In mostcases,thread scheduler
schedulesthe threadsaccordingtotheirpriority(knownaspreemptive scheduling).Butitisnot guaranteedbecause it
dependsonJVMspecifificationthatwhich schedulingitchooses.
3 constants defined in Thread class:
1. publicstaticintMIN_PRIORITY
2. publicstaticintNORM_PRIORITY
3. publicstaticintMAX_PRIORITY
Defaultpriorityof athreadis 5 (NORM_PRIORITY).The value of MIN_PRIORITYis1 and the value of MAX_PRIORITYis
10.
ExampleofpriorityofaThread:
1. class Multi10 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName(
));
4. System.out.println("running thread priority is:"+Thread.currentThread().g
etPriority());
5.
6. }
Page 14 of 31
7. public static void main(String args[]){
8. Multi10 m1=new Multi10();
9. Multi10 m2=new Multi10();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Daemon Thread:
There are twotypesof threadsuserthreadand daemonthread.The daemonthreadisa service providerthread.It
providesservicestothe userthread.Itslife dependsonthe userthreadsi.e.whenall the userthreadsdies,JVM
terminates thisthreadautomatically.
Points to remember for Daemon Thread:
 It providesservicestouserthreadsforbackgroundsupportingtasks.Ithas norole in life thantoserve user
threads.
 Its life dependsonuserthreads.
 It isa lowprioritythread.
Why JVM terminates the daemonthread ifthere is no userthread remaining?
The sole purpose of the daemonthreadisthat it providesservicestouserthreadforbackgroundsupportingtask.If
there isno userthread,whyshouldJVMkeeprunningthisthread.Thatiswhy JVMterminatesthe daemonthreadif
there isno userthread.
MethodsforDaemonthread:
The java.lang.Threadclassprovidestwomethodsrelatedtodaemonthread
 publicvoid setDaemon(booleanstatus):isusedto markthe currentthreadas daemonthreador userthread.
 publicbooleanisDaemon():isusedto checkthat current isdaemon.
SimpleexampleofDaemonthread:
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
Page 15 of 31
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.setDaemon(true);
11.
12. t1.start();
13. t2.start();
14. }
15. }
Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false
Note: If you wantto makea userthread as Daemon, it mustnot be started otherwiseit willthrow
IllegalThreadStateException.
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
Output:exception in thread main: java.lang.IllegalThreadStateException
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared resource. Synchronization is
better in case we want only one thread can access the shared resource at a time.
Why useSynchronization?
The synchronizationismainlyusedto
1. To preventthreadinterference.
2. To preventconsistencyproblem.
TypesofSynchronization
There are twotypesof synchronization
1. ProcessSynchronization
2. ThreadSynchronization
Here,we will discussonlythread synchronization.
Page 16 of 31
ThreadSynchronization
There are twotypesof threadsynchronizationmutual exclusiveandinter-threadcommunication.
 Mutual Exclusive
1. Synchronizedmethod.
2. Synchronizedblock.
3. staticsynchronization.
 Cooperation(Inter-threadcommunication)
Mutual Exclusive
Mutual Exclusive helpskeepthreadsfrominterferingwithone anotherwhilesharingdata.Thiscanbe done bythree
waysin java:
1. by synchronizedmethod
2. by synchronizedblock
3. by staticsynchronization
Understandingtheconceptof Lock
Synchronizationisbuiltaroundaninternal entityknownasthe lockor 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.
From Java5 the package java.util.concurrent.lockscontainsseverallockimplementations.
UnderstandingtheproblemwithoutSynchronization
In thisexample,there isnosynchronization,sooutputisinconsistent.Let'ssee the example:
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
Page 17 of 31
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class Use{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
100
10
200
15
300
20
400
25
500
Solutionbysynchronizedmethod
 If you declare anymethodassynchronized,itisknownassynchronizedmethod.
 Synchronizedmethodisusedtolockan objectforany sharedresource.
 Whena thread invokesasynchronizedmethod,itautomaticallyacquiresthe lockforthatobjectandreleasesit
whenthe methodreturns.
1. //Program of synchronized method.
2.
3. Class Table{
4.
5. synchronized void printTable(int n){//synchronized method
6. for(int i=1;i<=5;i++){
7. System.out.println(n*i);
8. try{
9. Thread.sleep(400);
10. }catch(Exception e){System.out.println(e);}
11. }
12.
13. }
14. }
Page 18 of 31
15.
16. class MyThread1 extends Thread{
17. Table t;
18. MyThread1(Table t){
19. this.t=t;
20. }
21. public void run(){
22. t.printTable(5);
23. }
24.
25. }
26. class MyThread2 extends Thread{
27. Table t;
28. MyThread2(Table t){
29. this.t=t;
30. }
31. public void run(){
32. t.printTable(100);
33. }
34. }
35.
36. class Use{
37. public static void main(String args[]){
38. Table obj = new Table();//only one object
39. MyThread1 t1=new MyThread1(obj);
40. MyThread2 t2=new MyThread2(obj);
41. t1.start();
42. t2.start();
43. }
44. }
Output: 5
10
15
20
25
100
200
300
400
500
SameExampleofsynchronizedmethodbyusingannonymousclass
In thisprogram,we have createdthe two threadsby anonymous class,solesscodingisrequired.
1. //Program of synchronized method by using annonymous class.
2.
3. Class Table{
4.
5. synchronized void printTable(int n){//synchronized method
6. for(int i=1;i<=5;i++){
7. System.out.println(n*i);
8. try{
9. Thread.sleep(400);
10. }catch(Exception e){System.out.println(e);}
11. }
12.
Page 19 of 31
13. }
14. }
15.
16. class Use{
17. public static void main(String args[]){
18. final Table obj = new Table();//only one object
19.
20. MyThread1 t1=new MyThread1(){
21. public void run(){
22. obj.printTable(5);
23. }
24. };
25. MyThread1 t2=new MyThread1(){
26. public void run(){
27. obj.printTable(100);
28. }
29. };
30.
31. t1.start();
32. t2.start();
33. }
34. }
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose youhave 50 linesof code inyourmethod, but you want to synchronize only 5 lines, you can use synchronized
block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.
Pointsto rememberforSynchronizedblock
 Synchronizedblockisusedtolockan objectforany sharedresource.
 Scope of synchronizedblockissmallerthanthe method.
Syntax to use synchronizedblock
1. synchronized (object reference expression) {
2. //code block
3. }
Page 20 of 31
Exampleofsynchronizedblock
Let's see the simple exampleof synchronizedblock.
1. //Program of synchronized block.
2.
3. class Table{
4.
5. void printTable(int n){
6. synchronized(this){//synchronized block
7. for(int i=1;i<=5;i++){
8. System.out.println(n*i);
9. try{
10. Thread.sleep(400);
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
14. }//end of the method
15. }
16.
17. class MyThread1 extends Thread{
18. Table t;
19. MyThread1(Table t){
20. this.t=t;
21. }
22. public void run(){
23. t.printTable(5);
24. }
25.
26. }
27. class MyThread2 extends Thread{
28. Table t;
29. MyThread2(Table t){
30. this.t=t;
31. }
32. public void run(){
33. t.printTable(100);
34. }
35. }
36.
37. class Use{
38. public static void main(String args[]){
39. Table obj = new Table();//only one object
40. MyThread1 t1=new MyThread1(obj);
41. MyThread2 t2=new MyThread2(obj);
42. t1.start();
43. t2.start();
44. }
45. }
Output:5
10
15
20
25
100
200
Page 21 of 31
300
400
500
SameExampleofsynchronizedblockbyusingannonymousclass:
1. //Program of synchronized block by using annonymous class.
2.
3. class Table{
4.
5. void printTable(int n){
6. synchronized(this){//synchronized block
7. for(int i=1;i<=5;i++){
8. System.out.println(n*i);
9. try{
10. Thread.sleep(400);
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
14. }//end of the method
15. }
16.
17. class Use{
18. public static void main(String args[]){
19. final Table obj = new Table();//only one object
20.
21. Thread t1=new Thread(){
22. public void run(){
23. obj.printTable(5);
24. }
25. };
26. Thread t2=new Thread(){
27. public void run(){
28. obj.printTable(100);
29. }
30. };
31.
32. t1.start();
33. t2.start();
34. }
35. }
Output:5
10
15
20
25
100
200
300
400
500
Page 22 of 31
Static synchronization
If you make any staticmethodas synchronized,the lockwill be onthe classnoton object.
Problemwithoutstatic synchronization
Suppose there are twoobjectsof a shared class(e.g.Table) namedobject1andobject2.In case of synchronized method
and synchronizedblock there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
commonobjectthat have a single lock.Butthere can be interference betweent1and t3 or t2 and t4 because t1acquires
anotherlockand t3 acquiresanother lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization
solves this problem.
Exampleofstatic synchronization
In thisexample we are applyingsynchronizedkeywordonthe staticmethodtoperformstatissynchrnization.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
Page 23 of 31
public void run(){
Table.printTable(1000);
}
}
class Use{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Page 24 of 31
Sameexampleof static synchronizationbyannonymousclass
In thisexample,we are usingannonymousclasstocreate the threads.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class Test {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
Page 25 of 31
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Synchronizedblockonaclasslock:
The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized method
printTable(int n) in class Table is equivalent to the following declaration:
1. static void printTable(int n) {
2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }
Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and
secondthreadiswaitingforan objectlockthat isacquiredbyfirstthread.Since,boththreadsare waiting for each other
to release the lock, the condition is called deadlock.
Page 26 of 31
ExampleofDeadlockinjava:
1. public class DeadlockExample {
2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);} catch (Exception e) {}
12.
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24. System.out.println("Thread 2: locked resource 2");
25.
26. try { Thread.sleep(100);} catch (Exception e) {}
27.
28. synchronized (resource1) {
29. System.out.println("Thread 2: locked resource 1");
30. }
31. }
32. }
33. };
34.
35.
36. t1.start();
37. t2.start();
38. }
39. }
40.
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
Page 27 of 31
Inter-thread communication (Cooperation):
Cooperation (Inter-thread communication) is all about making synchronized threads communicate with each other.
Cooperation(Inter-threadcommunication) isamechanisminwhichathreadis paused running in its critical section and
anotherthreadisallowed to enter (or lock) in the same critical section to be executed.It is implemented by following
methods of Object class:
 wait()
 notify()
 notifyAll()
1)wait()method:
Causescurrentthreadto release the lockandwaituntil eitheranotherthreadinvokesthe notify() methodorthe
notifyAll()methodforthisobject,oraspecifiedamountof time haselapsed.The currentthreadmustownthisobject's
monitor.Syntax:
 public final void wait()throws InterruptedException
 public final void wait(long timeout)throws InterruptedException
2)notify()method:
Wakesup a single threadthatiswaitingonthisobject'smonitor.If anythreadsare waitingonthisobject,one of them is
chosento be awakened.The choice isarbitraryandoccurs at the discretionof the implementation.Syntax:
 public final void notify()
3)notifyAll()method:
Wakesup all threadsthat are waitingonthisobject'smonitor.
 public final void notifyAll()
ExampleofInter threadCommunication:
1. public class Customer {
2. int amount=0;
3. int flag=0;
4. public synchronized int withdraw(int amount){
5. System.out.println(Thread.currentThread().getName()+" is going to withdr
aw");
6.
7. if(flag==0){
8. try{
9. System.out.println("waiting....");
10. wait();
11. }catch(Exception e){}
12. }
13. this.amount-=amount;
14. System.out.println("withdraw completed");
15. return amount;
Page 28 of 31
16. }
17.
18. public synchronized void deposit(int amount){
19. System.out.println(Thread.currentThread().getName()+"is going to depos
it");
20. this.amount+=amount;
21.
22. notifyAll();
23. System.out.println("deposit completed");
24. flag=1;
25. }
26.
27.
28. }
29.
30. public class SynMethod {
31. public static void main(String[] args) {
32. final Customer c=new Customer();
33.
34. Thread t1=new Thread(){
35. public void run(){
36. c.withdraw(5000);
37. System.out.println("After withdraw amount is"+c.amount);
38. }
39. };
40.
41. Thread t2=new Thread(){
42. public void run(){
43. c.deposit(9000);
44. System.out.println("After deposit amount is "+c.amount);
45. }
46. };
47.
48.
49. t1.start();
50. t2.start();
51.
52.
53. }
54. }
Output: Thread-0 is going to withdraw
waiting....
Thread-1 is going to deposit
deposit completed
After deposit amount is 9000
withdraw completed
After withdraw amount is 4000
Interrupting a Thread:
If any threadis insleepingorwaitingstate (i.e.sleep() orwait() isinvoked),callingthe interrupt() methodonthe thre ad,
breaksout the sleepingorwaitingstate throwingInterruptedException.If the threadisnotinthe sleepingorwaiting
state,callingthe interrupt()methodperformsnormal behaviouranddoesn'tinterruptthe threadbutsetsthe interrupt
Page 29 of 31
flagto true.Let's firstsee the methodsprovidedbythe Threadclassfor threadinterruption.
The 3 methods provided by the Thread class for interrupting a thread
 publicvoid interrupt()
 publicstatic booleaninterrupted()
 publicbooleanisInterrupted()
Example of interrupting a thread that stops working
In thisexample,afterinterruptingthe thread,we are propagatingit,soit will stopworking.If we don'twantto stopthe
thread,we can handle itwhere sleep() orwait() methodisinvoked.Let'sfirstsee the example where we are propagating
the exception.
1. class A extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. throw new RuntimeException("Thread interrupted..."+e);
8. }
9.
10. }
11.
12. public static void main(String args[]){
13. A t1=new A();
14. t1.start();
15. try{
16. t1.interrupt();
17. }catch(Exception e){System.out.println("Exception handled "+e);}
18.
19. }
20. }
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
Example of interrupting a thread that doesn't stop working
In thisexample,afterinterrupting the thread,we handle the exception,soitwill breakoutthe sleepingbutwill notstop
working.
1. class A extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
Page 30 of 31
6. }catch(InterruptedException e){
7. System.out.println("Exception handled "+e);
8. }
9. System.out.println("thread is running...");
10. }
11.
12. public static void main(String args[]){
13. A t1=new A();
14. t1.start();
15.
16. t1.interrupt();
17.
18. }
19. }
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
Example of interrupting thread that behaves normally
If thread isnot insleepingorwaitingstate,callingthe interrupt() methodsetsthe interruptedflagtotrue that can be
usedto stopthe thread bythe java programmerlater.
1. class A extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=5;i++)
5. System.out.println(i);
6. }
7.
8. public static void main(String args[]){
9. A t1=new A();
10. t1.start();
11.
12. t1.interrupt();
13.
14. }
15. }
Output:1
2
3
4
5
What about isInterrupted and interrupted method?
The isInterrupted() methodreturnsthe interruptedflageithertrue orfalse.The staticinterrupted()methodreturnsthe
interruptedflagafterthatitsetsthe flagtofalse if itistrue.
Page 31 of 31
1. class InterruptedDemo extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=2;i++){
5. if(Thread.interrupted()){
6. System.out.println("code for interrupted thread");
7. }
8. else{
9. System.out.println("code for normal thread");
10. }
11.
12. }//end of for loop
13. }
14.
15. public static void main(String args[]){
16.
17. InterruptedDemo t1=new InterruptedDemo();
18. InterruptedDemo t2=new InterruptedDemo();
19.
20. t1.start();
21. t1.interrupt();
22.
23. t2.start();
24.
25. }
26. }
Output:Code for interrupted thread
code for normal thread
code for normal thread
code for normal thread

More Related Content

PPTX
Internet Programming with Java
PDF
Java unit 12
PPT
Threads in Java
PDF
Java Thread Synchronization
PDF
javathreads
PPT
Thread
PPT
Threads in java
PPT
Synchronization.37
Internet Programming with Java
Java unit 12
Threads in Java
Java Thread Synchronization
javathreads
Thread
Threads in java
Synchronization.37

What's hot (19)

PPTX
Multithread Programing in Java
PPT
Java Threads and Concurrency
PDF
Programming with Threads in Java
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPT
Basic of Multithreading in JAva
PDF
Java threading
PPTX
Multi threading
PDF
Threads concept in java
PPSX
Multithreading in-java
PDF
Multithreading in Java
PDF
Multithreading Introduction and Lifecyle of thread
ODP
Multithreading In Java
PPTX
Java Thread & Multithreading
PPTX
Multithreading in java
PPT
Python multithreading session 9 - shanmugam
PPT
Learning Java 3 – Threads and Synchronization
PPTX
Multithreading in Java
PPT
Java Multithreading
Multithread Programing in Java
Java Threads and Concurrency
Programming with Threads in Java
Advanced Introduction to Java Multi-Threading - Full (chok)
Basic of Multithreading in JAva
Java threading
Multi threading
Threads concept in java
Multithreading in-java
Multithreading in Java
Multithreading Introduction and Lifecyle of thread
Multithreading In Java
Java Thread & Multithreading
Multithreading in java
Python multithreading session 9 - shanmugam
Learning Java 3 – Threads and Synchronization
Multithreading in Java
Java Multithreading
Ad

Similar to Class notes(week 9) on multithreading (20)

PDF
Class notes(week 9) on multithreading
PPT
multithreading, creating a thread and life cycle in java.ppt
PPTX
Concept of Java Multithreading-Partially.pptx
PPTX
Multithreading in Java Object Oriented Programming language
PPT
Thread model in java
PPTX
Java programming PPT. .pptx
PPT
multhi threading concept in oops through java
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
PPT
Runnable interface.34
PPTX
OOPS object oriented programming UNIT-4.pptx
PPTX
Threads in Java
PPTX
PDF
java-thread
PPTX
Multithreaded programming
PPTX
Multithreading
PPT
Session 7_MULTITHREADING in java example.ppt
PPT
Session 7_MULTITHREADING in java example.ppt
PPTX
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
PPTX
Java Multithreading.pptx
Class notes(week 9) on multithreading
multithreading, creating a thread and life cycle in java.ppt
Concept of Java Multithreading-Partially.pptx
Multithreading in Java Object Oriented Programming language
Thread model in java
Java programming PPT. .pptx
multhi threading concept in oops through java
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
Runnable interface.34
OOPS object oriented programming UNIT-4.pptx
Threads in Java
java-thread
Multithreaded programming
Multithreading
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Java Multithreading.pptx
Ad

More from Kuntal Bhowmick (20)

PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
PPT
1. introduction to E-commerce
DOCX
Computer graphics question for exam solved
PDF
DBMS and Rdbms fundamental concepts
PDF
Java questions for interview
PDF
Java Interview Questions
PDF
Operating system Interview Questions
PDF
Computer Network Interview Questions
PDF
C interview questions
PDF
C question
PDF
Distributed operating systems cs704 a class test
DOCX
Cs291 assignment solution
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
1. introduction to E-commerce
Computer graphics question for exam solved
DBMS and Rdbms fundamental concepts
Java questions for interview
Java Interview Questions
Operating system Interview Questions
Computer Network Interview Questions
C interview questions
C question
Distributed operating systems cs704 a class test
Cs291 assignment solution

Recently uploaded (20)

PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Welding lecture in detail for understanding
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
Sustainable Sites - Green Building Construction
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
R24 SURVEYING LAB MANUAL for civil enggi
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Operating System & Kernel Study Guide-1 - converted.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Lecture Notes Electrical Wiring System Components
Welding lecture in detail for understanding
UNIT-1 - COAL BASED THERMAL POWER PLANTS
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Model Code of Practice - Construction Work - 21102022 .pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Sustainable Sites - Green Building Construction
Automation-in-Manufacturing-Chapter-Introduction.pdf

Class notes(week 9) on multithreading

  • 1. Page 1 of 31 Class Notes on Multithreading (Week - 9) Contents:- Basicsof multithreading,mainthread,threadlifecycle,creationof multiplethreads,threadsynchronization, interthreadcommunication,deadlocksforthreads,suspending&resumingthreads. Multithreading in Java Multithreadingisaprocessof executingmultiple threadssimultaneously.Threadisbasicallya lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes. Multithreading is mostly used in games, animation etc. Multitasking Multitaskingisaprocessof executingmultiple taskssimultaneously.We use multitaskingtoutilize the CPU.Multitasking can be achievedbytwoways:  Process-basedMultitasking(Multiprocessing)  Thread-basedMultitasking(Multithreading) 1) Process-basedMultitasking(Multiprocessing)  Each process has itsown addressinmemoryi.e.eachprocessallocates separate memoryarea.  Processisheavyweight.  Cost of communicationbetweenthe processes ishigh.  Switchingfromone process toanotherrequire some time forsavingandloadingregisters,memorymaps, updatinglistsetc. 2) Thread-basedMultitasking(Multithreading)  Threadsshare the same addressspace.  Threadis lightweight.  Cost of communicationbetweenthe threadislow.  Note:At leastone processisrequiredforeachthread. What is Thread? A threadisa lightweightsubprocess,asmallestunitof processing.Itisaseparate pathof execution.Itsharesthe memoryareaof process. As showninthe above figure, thread(t1,t2 and t3) isexecutedinside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. Note:At a time onlyone thread isexecuted.
  • 2. Page 2 of 31 Life cycle of a Thread (Thread States) A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non - runnable andterminated.There isnorunningstate.Butforbetterunderstandingthe threads,we are explainingitin the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable(Blocked) 5. Terminated 1)New The thread isinnewstate if youcreate an instance of Threadclass butbefore the invocationof start() method. 2)Runnable The thread isinrunnable state afterinvocationof start() method,butthe threadschedulerhasnotselectedittobe the runningthread. 3)Running The thread isinrunningstate if the threadschedulerhasselectedit. 4)Non-Runnable(Blocked) Thisis the state whenthe threadisstill alive,butiscurrentlynoteligibletorun. 5)Terminated A threadisin terminatedordeadstate whenitsrun() methodexits. How to create thread: There are twowaysto create a thread: 1. By extendingThreadclass 2. By implementingRunnableinterface. Thread class: Threadclass provide constructorsandmethodstocreate and performoperationsonathread. Threadclassextends Objectclassand implementsRunnable interface.
  • 3. Page 3 of 31 CommonlyusedConstructorsofThread class:  Thread()  Thread(Stringname)  Thread(Runnabler)  Thread(Runnabler,Stringname) CommonlyusedmethodsofThreadclass: 1. publicvoid run():is usedto performactionfora thread. 2. publicvoid start(): starts the executionof the thread.JVMcallsthe run() methodonthe thread. 3. publicvoid sleep(longmiliseconds): Causesthe currentlyexecutingthreadtosleep(temporarilycease execution)forthe specifiednumberof milliseconds. 4. publicvoid join():waitsfora threadto die. 5. publicvoid join(longmiliseconds): waitsfora threadto die forthe specifiedmiliseconds. 6. publicint getPriority():returnsthe priorityof the thread. 7. publicint setPriority(intpriority): changesthe priorityof the thread. 8. publicString getName():returnsthe name of the thread. 9. publicvoid setName(Stringname): changesthe name of the thread. 10. publicThread currentThread(): returnsthe reference of currentlyexecutingthread. 11. publicint getId():returnsthe idof the thread. 12. publicThread.State getState():returnsthe state of the thread. 13. publicbooleanisAlive():testsif the threadisalive. 14. publicvoid yield():causesthe currentlyexecutingthreadobjecttotemporarilypause andallow otherthreadsto execute. 15. publicvoid suspend():isusedtosuspendthe thread(depricated). 16. publicvoid resume():isusedtoresume the suspendedthread(depricated). 17. publicvoid stop():is usedtostop the thread(depricated). 18. publicbooleanisDaemon():testsif the threadis a daemonthread. 19. publicvoid setDaemon(booleanb):marksthe threadas daemonor userthread. 20. publicvoid interrupt():interruptsthe thread. 21. publicbooleanisInterrupted(): testsif the threadhasbeeninterrupted. 22. publicstatic booleaninterrupted(): testsif the currentthreadhasbeeninterrupted. Runnableinterface: The Runnable interface shouldbe implementedbyanyclasswhose instancesare intendedtobe executedbyathread. Runnable interface have onlyone methodnamedrun(). 1. publicvoid run():is usedto performactionfora thread. Startinga thread: start() methodof Threadclass isusedto start a newlycreatedthread.Itperformsfollowingtasks:  A newthreadstarts(withnewcallstack).  The thread movesfromNewstate tothe Runnable state.  Whenthe threadgets a chance to execute,itstargetrun() methodwillrun.
  • 4. Page 4 of 31 1)ByextendingThreadclass: 1. class Multi extends Thread{ 2. public void run(){ 3. System.out.println("thread is running..."); 4. } 5. public static void main(String args[]){ 6. Multi t1=new Multi(); 7. t1.start(); 8. } 9. } Output:thread is running... Who makes yourclassobjectasthread object? Thread class constructor allocatesanewthreadobject. Whenyoucreate objectof Multi class, yourclass constructoris invoked (providedbyCompiler) from where Thread classconstructorisinvoked (bysuper() asfirststatement). Soyour Multi class objectisthreadobjectnow. 2)Byimplementingthe Runnableinterface: 1. class Multi3 implements Runnable{ 2. public void run(){ 3. System.out.println("thread is running..."); 4. } 5. 6. public static void main(String args[]){ 7. Multi3 m1=new Multi3(); 8. Thread t1 =new Thread(m1); 9. t1.start(); 10. } 11. } Output:thread is running... If you are notextendingthe Threadclass, yourclassobjectwouldnot be treatedasa threadobject. Soyouneedto explicitly create Threadclassobject. We are passingthe objectof yourclass thatimplementsRunnablesothatyourclass run() methodmayexecute. How to perform single task by multiple threads? If you have to performsingle taskbymanythreads,have onlyone run() method. Forexample: 1. //Program of performing single task by multiple threads 2. 3. class Multi extends Thread{ 4. public void run(){ 5. System.out.println("task one"); 6. } 7. public static void main(String args[]){ 8. Multi t1=new Multi(); 9. Multi t2=new Multi();
  • 5. Page 5 of 31 10. Multi t3=new Multi(); 11. 12. t1.start(); 13. t2.start(); 14. t3.start(); 15. } 16. } Output:task one task one task one 1. //Program of performing single task by multiple threads by implementing Runnable. 2. 3. class Multi3 implements Runnable{ 4. public void run(){ 5. System.out.println("task one"); 6. } 7. 8. public static void main(String args[]){ 9. Thread t1 =new Thread(new Multi3());//passing annonymous obj of Multi3 class 10. Thread t2 =new Thread(new Multi3()); 11. 12. t1.start(); 13. t2.start(); 14. 15. } 16. } Output:task one task one Note: Each thread runin a separatecallstack. Howto performmultipletasksbymultiple threads(multitasking inmultithreading)? If you have to performmultipletasksbymultiple threads,have multiplerun() methods. Forexample: 1. // Program of performing two tasks by two threads. 2. 3. class Simple1 extends Thread{ 4. public void run(){ 5. System.out.println("task one"); 6. } 7. } 8.
  • 6. Page 6 of 31 9. class Simple2 extends Thread{ 10. public void run(){ 11. System.out.println("task two"); 12. } 13. } 14. 15. class Test{ 16. public static void main(String args[]){ 17. Simple1 t1=new Simple1(); 18. Simple2 t2=new Simple2(); 19. 20. t1.start(); 21. t2.start(); 22. } 23. } Output:task one task two Sameexampleas abovebyannonymousclassthat implementsRunnableinterface: 1. //Program of performing two tasks by two threads. 2. 3. class Test{ 4. public static void main(String args[]){ 5. Runnable r1=new Runnable(){ 6. public void run(){ 7. System.out.println("task one"); 8. } 9. }; 10. 11. Runnable r2=new Runnable(){ 12. public void run(){ 13. System.out.println("task two"); 14. } 15. }; 16. 17. Thread t1=new Thread(r1); 18. Thread t2=new Thread(r2); 19. 20. t1.start(); 21. t2.start(); 22. } 23. } Output:task one task two The Thread Schedular:  The thread scheduleristhe partof the JVMthat decideswhichthreadshouldrun.  There isno guarantee thatwhichrunnable threadwill be chosentorunby the thread scheduler.  Onlyone threadat a time canrun in a single process.  The thread schedulermainlyusespreemptiveortime slicingschedulingtoschedule the threads.
  • 7. Page 7 of 31 What is the differencebetweenpreemptiveschedulingandtimeslicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher prioritytaskcomesintoexistence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Sleeping a thread (sleep() method): The sleep() methodof Threadclassisusedto sleepathreadfor the specifiedtime. Syntax of sleep() method: The Thread classprovidestwomethodsforsleepingathread:  publicstaticvoidsleep(longmiliseconds)throwsInterruptedException  publicstaticvoidsleep(longmiliseconds,intnanos)throwsInterruptedException 1. // Program of sleep() method 2. 3. class Multi extends Thread{ 4. public void run(){ 5. for(int i=1;i<5;i++){ 6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);} 7. System.out.println(i); 8. } 9. } 10. public static void main(String args[]){ 11. Multi t1=new Multi(); 12. Multi t2=new Multi(); 13. 14. t1.start(); 15. t2.start(); 16. } 17. } Output:1 1 2 2 3 3 4 4 5 5 As youknowwell thatat a time onlyone threadisexecuted.If yousleepathreadforthe specifiedtime, the thread schedulerpicksupanotherthreadandso on. Can we start a thread twice? No.Afterstaringa thread,it can neverbe startedagain.If you doesso,an IllegalThreadStateExceptionisthrown.For Example: 1. class Multi extends Thread{ 2. public void run(){ 3. System.out.println("running..."); 4. } 5. public static void main(String args[]){
  • 8. Page 8 of 31 6. Multi t1=new Multi(); 7. t1.start(); 8. t1.start(); 9. } 10. } Output:running Exception in thread "main" java.lang.IllegalThreadStateException What if we call run() method directly instead start() method?  Each thread startsin a separate call stack.  Invokingthe run() methodfrommainthread,the run() methodgoesontothe currentcall stackrather thanat the beginningof anewcall stack. 1. class Multi extends Thread{ 2. public void run(){ 3. System.out.println("running..."); 4. } 5. public static void main(String args[]){ 6. Multi t1=new Multi(); 7. t1.run();//fine, but does not start a separate call stack 8. } 9. } Output:running... 1. //Problem if you direct call run() method 2. 3. class Multi extends Thread{ 4. public void run(){ 5. for(int i=1;i<5;i++){ 6. try{Thread.sleep(500);}catch(InterruptedException e) 7. {System.out.println(e);} 8. System.out.println(i); 9. } 10. } 11. public static void main(String args[]){ 12. Multi t1=new Multi(); 13. Multi t2=new Multi(); 14. 15. t1.run();
  • 9. Page 9 of 31 16. t2.run(); 17. } 18. } Output:1 2 3 4 5 1 2 3 4 5 As youcan see inthe above programthat there isno context-switchingbecausehere t1andt2 will be treatedasnormal objectnotthreadobject. The join() method: The join() methodwaitsforathreadto die.Inother words,itcausesthe currentlyrunningthreadstostopexecuting until the threaditjoinswithcompletesitstask. Syntax: public void join()throws InterruptedException public void join(long miliseconds)throws InterruptedException 1. // Example of join() method. 2. 3. classMulti extends Thread{ 4. publicvoidrun(){ 5. for(inti=1;i<=5;i++){ 6. try{ 7. Thread.sleep(500); 8. }catch(Exception e){System.out.println(e);} 9. System.out.println(i); 10. } 11. } 12. publicstaticvoidmain(Stringargs[]){ 13. Multi t1=new Multi(); 14. Multi t2=new Multi(); 15. Multi t3=new Multi(); 16. t1.start(); 17. try{ 18. t1.join(); 19. }catch(Exception e){System.out.println(e);} 20. 21. t2.start(); 22. t3.start();
  • 10. Page 10 of 31 23. } 24. } Output:1 2 3 4 5 1 1 2 2 3 3 4 4 5 5 As youcan see inthe above example,when t1completesitstaskthent2 and t3 startsexecuting. 1. //Example of join(long miliseconds) method. 2. 3. class Multi extends Thread{ 4. public void run(){ 5. for(int i=1;i<=5;i++){ 6. try{ 7. Thread.sleep(500); 8. }catch(Exception e){System.out.println(e);} 9. System.out.println(i); 10. } 11. } 12. public static void main(String args[]){ 13. Multi t1=new Multi(); 14. Multi t2=new Multi(); 15. Multi t3=new Multi(); 16. t1.start(); 17. try{ 18. t1.join(1500); 19. }catch(Exception e){System.out.println(e);} 20. 21. t2.start(); 22. t3.start(); 23. } 24. } Output:1 2 3 1 4 1 2 5
  • 11. Page 11 of 31 2 3 3 4 4 5 5 In the above example,when t1iscompletesitstaskfor1500 milliseconds(3times) thent2andt3 starts executing. getName(),setName(String)andgetId() method: public String getName() public void setName(String name) public long getId() 1. class Multi6 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); 4. } 5. public static void main(String args[]){ 6. Multi6 t1=new Multi6(); 7. Multi6 t2=new Multi6(); 8. System.out.println("Name of t1:"+t1.getName()); 9. System.out.println("Name of t2:"+t2.getName()); 10. System.out.println("id of t1:"+t1.getId()); 11. 12. t1.start(); 13. t2.start(); 14. 15. t1.setName("Sonoo Jaiswal"); 16. System.out.println("After changing name of t1:"+t1.getName()); 17. } 18. } Output:Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... After changling name of t1:Sonoo Jaiswal running... ThecurrentThread()method: The currentThread() methodreturnsareference tothe currentlyexecutingthread object. Syntax: publicstaticThreadcurrentThread()
  • 12. Page 12 of 31 1. //Example of currentThread() method 2. 3. class Multi6 extends Thread{ 4. public void run(){ 5. System.out.println(Thread.currentThread().getName()); 6. } 7. } 8. public static void main(String args[]){ 9. Multi6 t1=new Multi6(); 10. Multi6 t2=new Multi6(); 11. 12. t1.start(); 13. t2.start(); 14. } 15. } Output:Thread-0 Thread-1 Naming a thread: The Thread classprovidesmethodstochange andgetthe name of a thread. 1. publicString getName():isusedto returnthe name of a thread. 2. publicvoid setName(Stringname): isusedto change the name of a thread. Example of naming a thread: 1. class Multi6 extends Thread{ 2. public void run(){ 3. System.out.println("running..."); 4. } 5. public static void main(String args[]){ 6. Multi6 t1=new Multi6(); 7. Multi6 t2=new Multi6(); 8. System.out.println("Name of t1:"+t1.getName()); 9. System.out.println("Name of t2:"+t2.getName()); 10. 11. t1.start(); 12. t2.start(); 13. 14. t1.setName("Sonoo Jaiswal"); 15. System.out.println("After changing name of t1:"+t1.getName()); 16. } 17. } Output: Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... After changling name of t1:Sonoo Jaiswal running...
  • 13. Page 13 of 31 The currentThread() method: The currentThread() methodreturnsareference tothe currentlyexecutingthreadobject. Syntaxof currentThread()method:  publicstatic Thread currentThread(): returnsthe reference of currentlyrunningthread. Exampleof currentThread()method: 1. class Multi6 extends Thread{ 2. public void run(){ 3. System.out.println(Thread.currentThread().getName()); 4. } 5. } 6. public static void main(String args[]){ 7. Multi6 t1=new Multi6(); 8. Multi6 t2=new Multi6(); 9. 10. t1.start(); 11. t2.start(); 12. } 13. } Output:Thread-0 Thread-1 Priority of a Thread (Thread Priority): Each thread hasa priority.Prioritiesare representedbyanumberbetween1and 10. In mostcases,thread scheduler schedulesthe threadsaccordingtotheirpriority(knownaspreemptive scheduling).Butitisnot guaranteedbecause it dependsonJVMspecifificationthatwhich schedulingitchooses. 3 constants defined in Thread class: 1. publicstaticintMIN_PRIORITY 2. publicstaticintNORM_PRIORITY 3. publicstaticintMAX_PRIORITY Defaultpriorityof athreadis 5 (NORM_PRIORITY).The value of MIN_PRIORITYis1 and the value of MAX_PRIORITYis 10. ExampleofpriorityofaThread: 1. class Multi10 extends Thread{ 2. public void run(){ 3. System.out.println("running thread name is:"+Thread.currentThread().getName( )); 4. System.out.println("running thread priority is:"+Thread.currentThread().g etPriority()); 5. 6. }
  • 14. Page 14 of 31 7. public static void main(String args[]){ 8. Multi10 m1=new Multi10(); 9. Multi10 m2=new Multi10(); 10. m1.setPriority(Thread.MIN_PRIORITY); 11. m2.setPriority(Thread.MAX_PRIORITY); 12. m1.start(); 13. m2.start(); 14. 15. } 16. } Output:running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1 Daemon Thread: There are twotypesof threadsuserthreadand daemonthread.The daemonthreadisa service providerthread.It providesservicestothe userthread.Itslife dependsonthe userthreadsi.e.whenall the userthreadsdies,JVM terminates thisthreadautomatically. Points to remember for Daemon Thread:  It providesservicestouserthreadsforbackgroundsupportingtasks.Ithas norole in life thantoserve user threads.  Its life dependsonuserthreads.  It isa lowprioritythread. Why JVM terminates the daemonthread ifthere is no userthread remaining? The sole purpose of the daemonthreadisthat it providesservicestouserthreadforbackgroundsupportingtask.If there isno userthread,whyshouldJVMkeeprunningthisthread.Thatiswhy JVMterminatesthe daemonthreadif there isno userthread. MethodsforDaemonthread: The java.lang.Threadclassprovidestwomethodsrelatedtodaemonthread  publicvoid setDaemon(booleanstatus):isusedto markthe currentthreadas daemonthreador userthread.  publicbooleanisDaemon():isusedto checkthat current isdaemon. SimpleexampleofDaemonthread: 1. class MyThread extends Thread{ 2. public void run(){ 3. System.out.println("Name: "+Thread.currentThread().getName()); 4. System.out.println("Daemon: "+Thread.currentThread().isDaemon()); 5. } 6. 7. public static void main(String[] args){
  • 15. Page 15 of 31 8. MyThread t1=new MyThread(); 9. MyThread t2=new MyThread(); 10. t1.setDaemon(true); 11. 12. t1.start(); 13. t2.start(); 14. } 15. } Output:Name: thread-0 Daemon: true Name: thread-1 Daemon: false Note: If you wantto makea userthread as Daemon, it mustnot be started otherwiseit willthrow IllegalThreadStateException. 1. class MyThread extends Thread{ 2. public void run(){ 3. System.out.println("Name: "+Thread.currentThread().getName()); 4. System.out.println("Daemon: "+Thread.currentThread().isDaemon()); 5. } 6. 7. public static void main(String[] args){ 8. MyThread t1=new MyThread(); 9. MyThread t2=new MyThread(); 10. t1.start(); 11. t1.setDaemon(true);//will throw exception here 12. t2.start(); 13. } 14. } Output:exception in thread main: java.lang.IllegalThreadStateException Synchronization Synchronization is the capabilility of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time. Why useSynchronization? The synchronizationismainlyusedto 1. To preventthreadinterference. 2. To preventconsistencyproblem. TypesofSynchronization There are twotypesof synchronization 1. ProcessSynchronization 2. ThreadSynchronization Here,we will discussonlythread synchronization.
  • 16. Page 16 of 31 ThreadSynchronization There are twotypesof threadsynchronizationmutual exclusiveandinter-threadcommunication.  Mutual Exclusive 1. Synchronizedmethod. 2. Synchronizedblock. 3. staticsynchronization.  Cooperation(Inter-threadcommunication) Mutual Exclusive Mutual Exclusive helpskeepthreadsfrominterferingwithone anotherwhilesharingdata.Thiscanbe done bythree waysin java: 1. by synchronizedmethod 2. by synchronizedblock 3. by staticsynchronization Understandingtheconceptof Lock Synchronizationisbuiltaroundaninternal entityknownasthe lockor 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. From Java5 the package java.util.concurrent.lockscontainsseverallockimplementations. UnderstandingtheproblemwithoutSynchronization In thisexample,there isnosynchronization,sooutputisinconsistent.Let'ssee the example: 1. Class Table{ 2. 3. void printTable(int n){//method not synchronized 4. for(int i=1;i<=5;i++){ 5. System.out.println(n*i); 6. try{ 7. Thread.sleep(400); 8. }catch(Exception e){System.out.println(e);} 9. } 10. 11. } 12. } 13. 14. class MyThread1 extends Thread{ 15. Table t; 16. MyThread1(Table t){ 17. this.t=t; 18. } 19. public void run(){ 20. t.printTable(5); 21. }
  • 17. Page 17 of 31 22. 23. } 24. class MyThread2 extends Thread{ 25. Table t; 26. MyThread2(Table t){ 27. this.t=t; 28. } 29. public void run(){ 30. t.printTable(100); 31. } 32. } 33. 34. class Use{ 35. public static void main(String args[]){ 36. Table obj = new Table();//only one object 37. MyThread1 t1=new MyThread1(obj); 38. MyThread2 t2=new MyThread2(obj); 39. t1.start(); 40. t2.start(); 41. } 42. } Output: 5 100 10 200 15 300 20 400 25 500 Solutionbysynchronizedmethod  If you declare anymethodassynchronized,itisknownassynchronizedmethod.  Synchronizedmethodisusedtolockan objectforany sharedresource.  Whena thread invokesasynchronizedmethod,itautomaticallyacquiresthe lockforthatobjectandreleasesit whenthe methodreturns. 1. //Program of synchronized method. 2. 3. Class Table{ 4. 5. synchronized void printTable(int n){//synchronized method 6. for(int i=1;i<=5;i++){ 7. System.out.println(n*i); 8. try{ 9. Thread.sleep(400); 10. }catch(Exception e){System.out.println(e);} 11. } 12. 13. } 14. }
  • 18. Page 18 of 31 15. 16. class MyThread1 extends Thread{ 17. Table t; 18. MyThread1(Table t){ 19. this.t=t; 20. } 21. public void run(){ 22. t.printTable(5); 23. } 24. 25. } 26. class MyThread2 extends Thread{ 27. Table t; 28. MyThread2(Table t){ 29. this.t=t; 30. } 31. public void run(){ 32. t.printTable(100); 33. } 34. } 35. 36. class Use{ 37. public static void main(String args[]){ 38. Table obj = new Table();//only one object 39. MyThread1 t1=new MyThread1(obj); 40. MyThread2 t2=new MyThread2(obj); 41. t1.start(); 42. t2.start(); 43. } 44. } Output: 5 10 15 20 25 100 200 300 400 500 SameExampleofsynchronizedmethodbyusingannonymousclass In thisprogram,we have createdthe two threadsby anonymous class,solesscodingisrequired. 1. //Program of synchronized method by using annonymous class. 2. 3. Class Table{ 4. 5. synchronized void printTable(int n){//synchronized method 6. for(int i=1;i<=5;i++){ 7. System.out.println(n*i); 8. try{ 9. Thread.sleep(400); 10. }catch(Exception e){System.out.println(e);} 11. } 12.
  • 19. Page 19 of 31 13. } 14. } 15. 16. class Use{ 17. public static void main(String args[]){ 18. final Table obj = new Table();//only one object 19. 20. MyThread1 t1=new MyThread1(){ 21. public void run(){ 22. obj.printTable(5); 23. } 24. }; 25. MyThread1 t2=new MyThread1(){ 26. public void run(){ 27. obj.printTable(100); 28. } 29. }; 30. 31. t1.start(); 32. t2.start(); 33. } 34. } Output: 5 10 15 20 25 100 200 300 400 500 Synchronized block Synchronized block can be used to perform synchronization on any specific resource of the method. Suppose youhave 50 linesof code inyourmethod, but you want to synchronize only 5 lines, you can use synchronized block. If you put all the codes of the method in the synchronized block, it will work same as the synchronized method. Pointsto rememberforSynchronizedblock  Synchronizedblockisusedtolockan objectforany sharedresource.  Scope of synchronizedblockissmallerthanthe method. Syntax to use synchronizedblock 1. synchronized (object reference expression) { 2. //code block 3. }
  • 20. Page 20 of 31 Exampleofsynchronizedblock Let's see the simple exampleof synchronizedblock. 1. //Program of synchronized block. 2. 3. class Table{ 4. 5. void printTable(int n){ 6. synchronized(this){//synchronized block 7. for(int i=1;i<=5;i++){ 8. System.out.println(n*i); 9. try{ 10. Thread.sleep(400); 11. }catch(Exception e){System.out.println(e);} 12. } 13. } 14. }//end of the method 15. } 16. 17. class MyThread1 extends Thread{ 18. Table t; 19. MyThread1(Table t){ 20. this.t=t; 21. } 22. public void run(){ 23. t.printTable(5); 24. } 25. 26. } 27. class MyThread2 extends Thread{ 28. Table t; 29. MyThread2(Table t){ 30. this.t=t; 31. } 32. public void run(){ 33. t.printTable(100); 34. } 35. } 36. 37. class Use{ 38. public static void main(String args[]){ 39. Table obj = new Table();//only one object 40. MyThread1 t1=new MyThread1(obj); 41. MyThread2 t2=new MyThread2(obj); 42. t1.start(); 43. t2.start(); 44. } 45. } Output:5 10 15 20 25 100 200
  • 21. Page 21 of 31 300 400 500 SameExampleofsynchronizedblockbyusingannonymousclass: 1. //Program of synchronized block by using annonymous class. 2. 3. class Table{ 4. 5. void printTable(int n){ 6. synchronized(this){//synchronized block 7. for(int i=1;i<=5;i++){ 8. System.out.println(n*i); 9. try{ 10. Thread.sleep(400); 11. }catch(Exception e){System.out.println(e);} 12. } 13. } 14. }//end of the method 15. } 16. 17. class Use{ 18. public static void main(String args[]){ 19. final Table obj = new Table();//only one object 20. 21. Thread t1=new Thread(){ 22. public void run(){ 23. obj.printTable(5); 24. } 25. }; 26. Thread t2=new Thread(){ 27. public void run(){ 28. obj.printTable(100); 29. } 30. }; 31. 32. t1.start(); 33. t2.start(); 34. } 35. } Output:5 10 15 20 25 100 200 300 400 500
  • 22. Page 22 of 31 Static synchronization If you make any staticmethodas synchronized,the lockwill be onthe classnoton object. Problemwithoutstatic synchronization Suppose there are twoobjectsof a shared class(e.g.Table) namedobject1andobject2.In case of synchronized method and synchronizedblock there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a commonobjectthat have a single lock.Butthere can be interference betweent1and t3 or t2 and t4 because t1acquires anotherlockand t3 acquiresanother lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem. Exampleofstatic synchronization In thisexample we are applyingsynchronizedkeywordonthe staticmethodtoperformstatissynchrnization. class Table{ synchronized static void printTable(int n){ for(int i=1;i<=10;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){} } } } class MyThread1 extends Thread{ public void run(){ Table.printTable(1); } } class MyThread2 extends Thread{ public void run(){ Table.printTable(10); } } class MyThread3 extends Thread{ public void run(){ Table.printTable(100); } } class MyThread4 extends Thread{
  • 23. Page 23 of 31 public void run(){ Table.printTable(1000); } } class Use{ public static void main(String t[]){ MyThread1 t1=new MyThread1(); MyThread2 t2=new MyThread2(); MyThread3 t3=new MyThread3(); MyThread4 t4=new MyThread4(); t1.start(); t2.start(); t3.start(); t4.start(); } } Output: 1 2 3 4 5 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 100 200 300 400 500 600 700 800 900 1000 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
  • 24. Page 24 of 31 Sameexampleof static synchronizationbyannonymousclass In thisexample,we are usingannonymousclasstocreate the threads. 1. class Table{ 2. 3. synchronized static void printTable(int n){ 4. for(int i=1;i<=10;i++){ 5. System.out.println(n*i); 6. try{ 7. Thread.sleep(400); 8. }catch(Exception e){} 9. } 10. } 11. } 12. 13. public class Test { 14. public static void main(String[] args) { 15. 16. Thread t1=new Thread(){ 17. public void run(){ 18. Table.printTable(1); 19. } 20. }; 21. 22. Thread t2=new Thread(){ 23. public void run(){ 24. Table.printTable(10); 25. } 26. }; 27. 28. Thread t3=new Thread(){ 29. public void run(){ 30. Table.printTable(100); 31. } 32. }; 33. 34. Thread t4=new Thread(){ 35. public void run(){ 36. Table.printTable(1000); 37. } 38. }; 39. t1.start(); 40. t2.start(); 41. t3.start(); 42. t4.start(); 43. 44. } 45. } Output: 1 2 3 4 5
  • 25. Page 25 of 31 6 7 8 9 10 10 20 30 40 50 60 70 80 90 100 100 200 300 400 500 600 700 800 900 1000 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 Synchronizedblockonaclasslock: The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration: 1. static void printTable(int n) { 2. synchronized (Table.class) { // Synchronized block on class A 3. // ... 4. } 5. } Deadlock: Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and secondthreadiswaitingforan objectlockthat isacquiredbyfirstthread.Since,boththreadsare waiting for each other to release the lock, the condition is called deadlock.
  • 26. Page 26 of 31 ExampleofDeadlockinjava: 1. public class DeadlockExample { 2. public static void main(String[] args) { 3. final String resource1 = "ratan jaiswal"; 4. final String resource2 = "vimal jaiswal"; 5. // t1 tries to lock resource1 then resource2 6. Thread t1 = new Thread() { 7. public void run() { 8. synchronized (resource1) { 9. System.out.println("Thread 1: locked resource 1"); 10. 11. try { Thread.sleep(100);} catch (Exception e) {} 12. 13. synchronized (resource2) { 14. System.out.println("Thread 1: locked resource 2"); 15. } 16. } 17. } 18. }; 19. 20. // t2 tries to lock resource2 then resource1 21. Thread t2 = new Thread() { 22. public void run() { 23. synchronized (resource2) { 24. System.out.println("Thread 2: locked resource 2"); 25. 26. try { Thread.sleep(100);} catch (Exception e) {} 27. 28. synchronized (resource1) { 29. System.out.println("Thread 2: locked resource 1"); 30. } 31. } 32. } 33. }; 34. 35. 36. t1.start(); 37. t2.start(); 38. } 39. } 40. Output: Thread 1: locked resource 1 Thread 2: locked resource 2
  • 27. Page 27 of 31 Inter-thread communication (Cooperation): Cooperation (Inter-thread communication) is all about making synchronized threads communicate with each other. Cooperation(Inter-threadcommunication) isamechanisminwhichathreadis paused running in its critical section and anotherthreadisallowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:  wait()  notify()  notifyAll() 1)wait()method: Causescurrentthreadto release the lockandwaituntil eitheranotherthreadinvokesthe notify() methodorthe notifyAll()methodforthisobject,oraspecifiedamountof time haselapsed.The currentthreadmustownthisobject's monitor.Syntax:  public final void wait()throws InterruptedException  public final void wait(long timeout)throws InterruptedException 2)notify()method: Wakesup a single threadthatiswaitingonthisobject'smonitor.If anythreadsare waitingonthisobject,one of them is chosento be awakened.The choice isarbitraryandoccurs at the discretionof the implementation.Syntax:  public final void notify() 3)notifyAll()method: Wakesup all threadsthat are waitingonthisobject'smonitor.  public final void notifyAll() ExampleofInter threadCommunication: 1. public class Customer { 2. int amount=0; 3. int flag=0; 4. public synchronized int withdraw(int amount){ 5. System.out.println(Thread.currentThread().getName()+" is going to withdr aw"); 6. 7. if(flag==0){ 8. try{ 9. System.out.println("waiting...."); 10. wait(); 11. }catch(Exception e){} 12. } 13. this.amount-=amount; 14. System.out.println("withdraw completed"); 15. return amount;
  • 28. Page 28 of 31 16. } 17. 18. public synchronized void deposit(int amount){ 19. System.out.println(Thread.currentThread().getName()+"is going to depos it"); 20. this.amount+=amount; 21. 22. notifyAll(); 23. System.out.println("deposit completed"); 24. flag=1; 25. } 26. 27. 28. } 29. 30. public class SynMethod { 31. public static void main(String[] args) { 32. final Customer c=new Customer(); 33. 34. Thread t1=new Thread(){ 35. public void run(){ 36. c.withdraw(5000); 37. System.out.println("After withdraw amount is"+c.amount); 38. } 39. }; 40. 41. Thread t2=new Thread(){ 42. public void run(){ 43. c.deposit(9000); 44. System.out.println("After deposit amount is "+c.amount); 45. } 46. }; 47. 48. 49. t1.start(); 50. t2.start(); 51. 52. 53. } 54. } Output: Thread-0 is going to withdraw waiting.... Thread-1 is going to deposit deposit completed After deposit amount is 9000 withdraw completed After withdraw amount is 4000 Interrupting a Thread: If any threadis insleepingorwaitingstate (i.e.sleep() orwait() isinvoked),callingthe interrupt() methodonthe thre ad, breaksout the sleepingorwaitingstate throwingInterruptedException.If the threadisnotinthe sleepingorwaiting state,callingthe interrupt()methodperformsnormal behaviouranddoesn'tinterruptthe threadbutsetsthe interrupt
  • 29. Page 29 of 31 flagto true.Let's firstsee the methodsprovidedbythe Threadclassfor threadinterruption. The 3 methods provided by the Thread class for interrupting a thread  publicvoid interrupt()  publicstatic booleaninterrupted()  publicbooleanisInterrupted() Example of interrupting a thread that stops working In thisexample,afterinterruptingthe thread,we are propagatingit,soit will stopworking.If we don'twantto stopthe thread,we can handle itwhere sleep() orwait() methodisinvoked.Let'sfirstsee the example where we are propagating the exception. 1. class A extends Thread{ 2. public void run(){ 3. try{ 4. Thread.sleep(1000); 5. System.out.println("task"); 6. }catch(InterruptedException e){ 7. throw new RuntimeException("Thread interrupted..."+e); 8. } 9. 10. } 11. 12. public static void main(String args[]){ 13. A t1=new A(); 14. t1.start(); 15. try{ 16. t1.interrupt(); 17. }catch(Exception e){System.out.println("Exception handled "+e);} 18. 19. } 20. } Output:Exception in thread-0 java.lang.RuntimeException: Thread interrupted... java.lang.InterruptedException: sleep interrupted at A.run(A.java:7) Example of interrupting a thread that doesn't stop working In thisexample,afterinterrupting the thread,we handle the exception,soitwill breakoutthe sleepingbutwill notstop working. 1. class A extends Thread{ 2. public void run(){ 3. try{ 4. Thread.sleep(1000); 5. System.out.println("task");
  • 30. Page 30 of 31 6. }catch(InterruptedException e){ 7. System.out.println("Exception handled "+e); 8. } 9. System.out.println("thread is running..."); 10. } 11. 12. public static void main(String args[]){ 13. A t1=new A(); 14. t1.start(); 15. 16. t1.interrupt(); 17. 18. } 19. } Output:Exception handled java.lang.InterruptedException: sleep interrupted thread is running... Example of interrupting thread that behaves normally If thread isnot insleepingorwaitingstate,callingthe interrupt() methodsetsthe interruptedflagtotrue that can be usedto stopthe thread bythe java programmerlater. 1. class A extends Thread{ 2. 3. public void run(){ 4. for(int i=1;i<=5;i++) 5. System.out.println(i); 6. } 7. 8. public static void main(String args[]){ 9. A t1=new A(); 10. t1.start(); 11. 12. t1.interrupt(); 13. 14. } 15. } Output:1 2 3 4 5 What about isInterrupted and interrupted method? The isInterrupted() methodreturnsthe interruptedflageithertrue orfalse.The staticinterrupted()methodreturnsthe interruptedflagafterthatitsetsthe flagtofalse if itistrue.
  • 31. Page 31 of 31 1. class InterruptedDemo extends Thread{ 2. 3. public void run(){ 4. for(int i=1;i<=2;i++){ 5. if(Thread.interrupted()){ 6. System.out.println("code for interrupted thread"); 7. } 8. else{ 9. System.out.println("code for normal thread"); 10. } 11. 12. }//end of for loop 13. } 14. 15. public static void main(String args[]){ 16. 17. InterruptedDemo t1=new InterruptedDemo(); 18. InterruptedDemo t2=new InterruptedDemo(); 19. 20. t1.start(); 21. t1.interrupt(); 22. 23. t2.start(); 24. 25. } 26. } Output:Code for interrupted thread code for normal thread code for normal thread code for normal thread