Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
78 views
23 pages
8 Multi Threading Enhancementspdf PDF Free
Uploaded by
Java Developer
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save _8-multi-threading-enhancementspdf-pdf-free For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
78 views
23 pages
8 Multi Threading Enhancementspdf PDF Free
Uploaded by
Java Developer
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save _8-multi-threading-enhancementspdf-pdf-free For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 23
Search
Fullscreen
Core Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements CIP / OCIP Study Material Chanter 8: Multi Threading Enhancements DURGA wmtech (Sun certified & Realtime Expert! DURGA SOFTWARE SOLUTIONS WWW.durgasofLcom Ph: 9246212143 8096969696 [7 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Multi Threading Enhancements| 8.1) ThreadGroup 8.2) ThreadLocal 8.3) java.util.concurrent.locks package >Lock(l) ->ReentrantLock(C ) 8.4) Thread Pools 8.5) Callable and Future ThreadGrow + Based on the Functionality we can Group Threads into a Single Unit which is Nothing but ThreadGroup ie. ThreadGroup Represents a Set of Threads. + In Addition a ThreadGroup can Also contains Other SubThreadGroups. | 15 6 t7 I subThreadGroup ThreadGroup + ThreadGroup Class Present in java.lang Package and it is the Direct Child Class of Object. © ThreadGroup provides a Convenient Way to Perform Common Operation for all Threads belongs to a Particular Group. Eg:Stop All Consumer Threads. Suspend All Producer Threads. [7 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Constructors: 1) ThreadGroup g = new ThreadGroup(String gname); ‘© Createsa New ThreadGroup. ‘+ The Parent of this New Group is the ThreadGroup of Currently Running Thread. 2) ThreadGroup g = new ThreadGroup(ThreadGrouppg, String gname); © Creates a New ThreadGroup. ‘+ The Parent of this ThreadGroup is the specified ThreadGroup. Note: + In Java Every Thread belongs to Some Group. «Every ThreadGroup is the Child Group of System Group either Directly OR Indirectly. Hence SystemGroup Acts as Root for all ThreadGroup’s in Java. «System ThreadGroup Represents System Level Threads Like ReferenceHandler, SignalDispatcher, Finalizer, AttachListener Ete. ThreadGroup || ReferenceHandler || signalDispatcher iS Main Child Child SubThreadGroup Thread |] Thread1 || Thread2 Class: Thread 1 Thread 2 Thresd 3 7g | DURGASOFT, # 202.2" Floor HUDA Waitrivanam Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements classThreadGroupDemo { public static vold main(String] args) { system. out.printin Thread.currentThread\).getThreadGroup().getName()); system. out.printinThread.current Thread().getThreadGroup().getParent().getName()); ThreadGrouppg = new ThreadGroup("Parent Group"); system.out.printin(pg.getParent().getName()); ThreadGroup cg = new ThreadGroup(pg, “Child Group"); main system. out.printin(eg.getParent().getName()); system d main } Parent Group Parent Group Important Methods of ThreadGroup Class: 1) String getName():Returns Name of the ThreadGroup, 2) imtgetMaxPriority):Returns the Maximum Priority of ThreadGroup. 3) void setMaxPriority( ‘© To Set Maximum Priority of ThreadGroup. + The Default Maximum Priority is 10. + Threads in the ThreadGroup that Already have Higher Prio but Newly Added Threads this MaxPriority is Applicable ; Not effected BO | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements classThreadGroupDemo { public static void main(String{] args) { ThreadGroup of = new ThreadGroup("ta"); Thread tt = new Thread(gt, "Thread 1"); Thread t2 = new Thread(g1, "Thread 2"); gt.setMaxPriority(3); Thread t3 = new Thread(at, "Thread 3"); system. out.printin(tt.getPriority());> 5 system.out.printin(t2.getPriority())> 5 system. out printin(t3.getPriority());> 3 4) ThreadGroupgetParent(): Returns Parent Group of Current ThreadGroup, 5) void listQ: It Prints Information about ThreadGroup to the Console. 6) intactiveCount): Returns Number of Active Threads Present in the ThreadGroup. 7) intactiveGroupCount(): It Returns Number of Active ThreadGroups Present in the Current ThreadGroup. 8) imt enumerate(Thread{] t): To Copy All Active Threads of this Group into provided Thread Array. In this Case SubThreadGroup Threads also will be Considered. 9) int enumerate(ThreadGroup[] g): To Copy All Active SubThreadGroups into ‘ThreadGroupArray. 10) booleanisDaemon(): 11) yoid setDaemon(boolean b): 12)yoid interrupt): To Interrupt All Threads Present in the ThreadGroup. 13) void destroy): To Destroy ThreadGroup and its SubThreadGroups. By | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements classMyThread extends Thread { MyThread(ThreadGroup g, String name) { super(g, name); ? public void run(){ System.out.printin("Child Thread”); try Thread sleep(2000); } catch (InterruptedException e) } ) classThreadGroupDemo { public static void main(String] args) throws Interruptedéxception { ThreadGrouppg = new ThreadGroup("Parent Group"); ThreadGroup cg = new ThreadGroup(pg, "Child Group"); MyThread t1 = new MyThread(pg, “Child Thread 1"); MyThread t2 = new MyThread{(pg, "Child Thread 2"); tHstart(); t2start() System.out.printin(pg.activeCount(); System.out.printin(pg.activeGroupCount()}; Paslst(); Thread sleep(5000); System.out.printin(pg.activeCount(); Pa.list(); java.lang.ThreadGroup{name=Parent Group,maxpri=10] ‘Thread{Child Thread 1,5,Parent Group] Thread[Child Thread 2,5,Parent Group] java.lang.ThreadGroup{name=Child Group,maxpri=10] Child Thread Child Thread 0 java.lang.ThreadGroup[name=Parent Group,maxpri=10] java.lang.ThreadGroupfname=Child Group,maxpri=10] 2 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Vrite a Program to Display All Thread Names belongs to System Group classThreadGroupDemo { public static vold main(string{] args) { ThreadGroup system = Thread.currentThreadi).getThreadGroup().getParent{); Threadl] t= new Threadfsystem.activeCount()}; system.enumerate(t); for (Thread tt: t){ system.out.printin(t1 getName()+"-—-~"#t1.isDaemon(); Reference Handler Finalizer——-true Signal Dispatcher-—-—true Attach Listener-etrue main——false rue ThreadLocal: ThreadLocalProvides ThreadLocal Variables. ‘ThreadLocal Class Maintains Values for Thread Basis. + Each ThreadLocal Object Maintains a Separate Value Like userID, transactionIDEte for Each Thread that Accesses that Object. © Thread can Access its Local Value, can Mani its Value. «In Every Part of the Code which is executed by the Thread we can Access its Local Variables. + Consider a Servlet which Calls Some Business Methods. we have a Requirement to generate a Unique transactionID for Each and Every Request and we have to Pass this transactionID to the Business Methods for Logging Purpose. «For this Requirement we can Use ThreadLocal to Maintain a Separate transactionID for Every Request and for Every Thread. Note: '* ThreadLocal Class introduced in 1.2 Version, '* ThreadLocal can be associated with Thread Scope. '® All the Code which is executed by the Thread has Access to Corresponding ThreadLocal Variables. '* A Thread cam Access its Own Local Variables and can’t Access Other Threads Local Variables. * Once Thread Entered into Dead State All Local Variables are by Default Eligible for Garbage Collection. Constructor:ThreadLocaltl = new ThreadLocal(); Creates a ThreadLocal Variable. Ba | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Methods: 1) Object get); Returns the Value of ThreadLocal Variable associated with Current Thread. 2) Object imitialValued; © Returns the initialValue of ThreadLocal Variable of Current Thread. © The Default Implementation of initialValue() Returns null. © To Customize Our initialValue we have to Override initialValue(. 3) void set(Object newValue);To Set a New Value, 4) void remove(): ‘© To Remove the Current Threads Local Variable Value ‘+ After Remove if we are trying to Access it will be reinitialized Once Again by invoking its initialValue(). + This Method Newly Added in 1.5 Version. classThreadLocalDemo { public static void main(String{] args) { ThreadLocaltl = new ThreadLocal(); system.out.printin(t.get(); //null tset("Durga"); system.out printin(th. get()); //Durga ‘hremove(); system.out.printin(tl.get(); //null } } Overriding of intialValue() classThreadLocalDemo { public static void main(String] args) { ThreadLocaltl = new ThreadLocal() { protected Object initialValue() { return "abe"; } % System.out.printin(th.get(); /abe tset("Durga"); System.out.printn(tl.get()); //Durga tremove(); System. out printin(t.get(); /abe } } Bd | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements classCustomerThread extends Thread { static Integer custlD = 0; private static ThreadLocalt! = new ThreadLocal() { protected Integer initilValue() { return +#custlD; ) ‘ CustomerThreadl( string name) { super(name); ? public void run(){ for (int 20; ie5; +4) { 0P(Thread.currentThreadl).getName()+" Executing with Customer ID:"+t.get()); ) } } classThreadLocalDemo { Public static void main(Stringf] args) { CustomerThread ct = new CustomerThread{"‘CustomerThread - 1"); CustomerThread c2 = new CustomerThread|"‘CustomerThread - 2"); CustomerThread c3 = new CustomerThread("CustomerThread - 3"); CustomerThread c4 = new CustomerThread("CustomerThread - 4"); ct.start(; estat): CustomerThread - 1 Executing with Customer ID:1 cBstart(); CustomerThread - 1 Executing with Customer ID:1 cAstart(); CustomerThread - 1 Executing with Customer ID:1 } CustomerThread - 1 Executing with Customer ID:1 ) CustomerThread - 1 Executing with Customer ID:1 CustomerThread - 2 Executing with Customer ID:2 CustomerThread - 2 Executing with Customer ID:2 CustomerThread - 2 Executing with Customer 1D:2, Customer Thread - 2 Executing with Customer I CustomerThread - 2 Executing with Customer I 2 Customer Thread - 3 Executing with Customer 1D:3, Customer Thread - 3 Executing with Customer ID:3, CustomerThread - 3 Executing with Customer ID:3, CustomerThread - 3 Executing with Customer ID:3, CustomerThread - 3 Executing with Customer 1D:3, CustomerThread - 4 Executing with Customer 1D:4 CustomerThread - 4 Executing with Customer 1D:4 CustomerThread - 4 Executing with Customer 1D:4 Customer Thread - 4 Executing with Customer ID:4 Customer Thread - 4 Executing with Customer I CustomerThread - 4 Executing with Customer 1D:4 Bi | DURGASOFT, # 202.2" Floor HUDA Waitrivanam Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements In the Above Program for Every Customer Thread a Separate customerID will be maintained by ThreadLocal Object. ThreadLocalVs Inheritanc «Parent Threads ThreadLocal Variables are by Default Not Available to the Child Threads. «© Ifwe want to Make Parent Threads Local Variables Available to Child Threads we should go for InheritableThreadLocal Class. # Itiy the Child Clays of ThreadLocal Class. © By Default Child Thread Values are Same as Parent Thread Values but we can Provide Customized Values for Child Threads by Overriding childValue(. Constructor:InheritableThreadLocalitl = new InheritableThreadLocal() InberitableThreadLocal is the Child Class of ThreadLocal and Hence All Methods Present in ThreadLocal by Default Available to the InheritableThreadLocal, Metho yublic Object childValue(Object pvalue); classParentThread extends Thread { public static InheritableThreadLocalitl = new InheritableThreadLocal() { public Object childValue(Object p) { return "cc"; } } public void run() { Itlset("pp"); system.out.printin("Parent Thread ~"sitl.get() ChildThreadct = new ChildThread(); ct-start() ) classChildThread extends Thread { public void run() { ‘System.out.printin("Child Thread --"+ParentThread.itl.get()); } } classThreadLocalDemo { Public static void main(Stringf] args) { ParentThreadot = new ParentThread(); ptstart(); ? Parent Threa ) Child Thread. Be | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements CEN CAU Ree LRA est Problems with Traditional synchronized Key Word «Ifa Thread Releases the Lock then which waiting Thread will get that Lock we are Not having any Control on this. © We can’t Specify Maximum waiting Time for a Thread to get Lock so that it Wait until getting Lock, which May Effect Performance of the System and Causes Dead Lock. We are Not having any Flexibility to Try for Lock without waiting There is No API to List All Waiting Threads for a Lock. + The synchronized Key Word Compulsory we have to Define within a Method and it is Not Possible to Declare Over Multiple Methods. + To Overcome Above Problems SUN People introduced java.util.concurrent.locks Package in 1.5 Version. # It Also Provides Several Enhancements to the Programmer to Provide More Control on Concurrency. Lock(): * A Lock Object is Similar to Implicit Lock acquired by a Thread to Execute synchronized Method OR synchronized Block * Lock Implementations Provide More Exten Implicit Locks. Operations than Traditional Important Methods of Lock Interface 1) void lock0: © It Locks the Lock Object. © If Lock Object is Already Locked by Other Thread then it will wait until it is Unlocked. 2) booleantryLock(): + To Acquire the Lock ifit is Available. If the Lock is Available then Thread Acquires the Lock and Returns true. If the Lock Unavailable then this Method Returns false and Continue its Execution. «In this Case Thread is Never Blocked. if (L.tryLock()) { Perform Safe Operations + else { Perform Alternative Operations } By | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements 3) boolentryLock(long time, TimeUnit unit): © To Acquire the Lock if't is Available. © Ifthe Lock is Unavailable then Thread can Wait until specified Amount of Time. Still if the Lock is Unavailable then Thread can Continue its Execution. Eg: if (LtryLock(1000, TimeUnit SECONDS) {} isan enum Present in java.util. concurrent Package, enumTimeUnit { DAYS, HOURS, MINUTES, SECONDS, MILLI SECONDS, MICRO SECONDS, NANO SECONDS; } 4) void lockInterruptediy(): Acquired the Lock Unless the Current Thread is Interrupted. Acquires the Lock if it is Available and Returns Immediately. Ifit is Unavailable then the Thread will wait while waiting if itis Interrupted then it won't get the Lock. 5) void unlock(: To Release the Lock. ReentrantLock «It implements Lock Interface and it is the Direct Child Class of an Object. © Reentrant Means a Thread can acquires Same Lock Multiple Times without any Issue. # Internally ReentrantLock Increments Threads Personal Count whenever we Call lock and Decrements Counter whenever we Call unlock() and Lock will be Released whenever Count Reaches ‘0’. ntLockr] = new ReentrantLock( Creates an Instance of ReentrantLock. 2) ReentramtLockr] = new ReentrantLock(boolean fairness): © Creates an Instance of ReentrantLock with the Given Fairness Policy. ‘+ If Fairness is true then Longest Waiting Thread can acquired Lock Once it is Avaiable i.e. if follows First - In First ~ Out. ‘+ If Fairness is false then we can’t give any Guarantee which Thread will get the Lock Once it is Available. Note: If we are Not specifying any Fairness Property then by Default it is Not Fair. Ba | DURGASOFT, # 202.2" Floor HUDA Waitrivanam Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Which of the following 2 Lines are Equal? ReentrantLockrl = new ReentrantLock(); Vv ReentrantLockrl = new ReentrantLock(true); ReentrantLockrl = new ReentrantLock(false); V_ Important Methods of ReentrantLock 1) void lockO: 2) booleantryLockQ: 3) booleantryLock(long L, TimeUnit t): 4) void lockInterruptediv(): 5) void unlock: + To Realease the Lock. + Ifthe Current Thread is Not Owner of the Lock then we will get Runtime Exception Saying IllegalMonitorStateException. 6) intgetHoldCount(); Returns Number of Holds on this Lock by Current Thread. 7) booleanisHeldByCurrentThread(; Returns true if'and Only if Lock is Hold by Current Thread. 8) intgetQueueLength(); Returns the Number of Threads waiting for the Lock. 9) Collection getQuewedThreads(); Returns a Collection containing Thread Objects which are waiting to get the Lock. 10) booleanhasQueued Threads; Returns true if any Thread waiting to get the Lock. 11) booleanisLockedQ): Returns true if the Lock acquired by any Thread. 12) booleanisPair():Returns true if the Lock’s Fairness Set to true. 13) Thread getOwner();Returns the Thread which acquires the Lock. 9 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements importjava.uti.concurrent.locks.ReentrantLock; class Test { Public static vold main(Stringl] args) { ReentrantLock I = new ReentrantLock(); Hock(); Llock0); System.out.printin(LisLocked()); //true system.out.printin(L.isHeldByCurrentThread(); //true System.out.printin(l.getQueueLength());//0 LLunlock); System.out.printin(l.getHoldcount()); 1/4 System.out.printin(LisLocked()); //true LLunlock); System.out.printin(L.isLocked()); / false System.out.printin(LisFai(); //false 0 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements importjava.uti.concurrent.locks.ReentrantLock; class Display { ReentrantLock | = new ReentrantLock(true); public void wish(String name) { Lock();> 1 for(int 120; 15; +4) { Good Morning i ry “ Dhoni Srstom.out printin(""Good Morning"); Good Morning 7 Dhoni ; Thread.sleep(2000); Good Morning Dhoni catch(InterruptedException e) {} system.out.printin(name) Good Morning ) Good M i . $ood Morning , Lunlock();> 2 ore } Good Morning ‘Yuva Raj Classy Tread tends Thread { Good Morning string name; Bee i MyThread(Display 4, String name) { aR this.d= d: Yuva Raj this.name = name; Good Morning Yuva Raj Good Morning Yuva Raj Good Morning ViratKoil Good Morning Viratk obit Good Morning Viratkohl ? public void run() { d.wish(name); } classReentrantLockDemo { public static void main(Stringf] aras) { Display d= new Display(); MyThread t1 = new MyThread(d, “Dhoni"); Good Morni MyThread t2 = new MyThread(d, “Yuva Raf Vietkoht ‘MyThread t3 = new MyThread(d, “ViratKohli"); ratk oh Good Morning thastart)); Viratkonit start); a“ tBstart(); If we Comment Both Lines 1 and 2 then All Threads will be executed Simultaneously and Hence we will get Irregular Output. If we are Not Commenting then the Threads will be executed One by One and Hence we will get Regular Output 7 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Demo Program To Demonstrate tryLock(): importjava.utl.concurrent.locks ReentrantLock; classMyThread extends Thread { staticReentrantLock | = new ReentrantLock\); MyThread(string name) { super(name); ? public void runt) { if(-tryLock()) { SOP(Thread.currentThreadl).getName()+" Got Lock and Performing Safe Operations"); tyt Thread.sleep(2000); } catch(Interruptedxception e) {} Luntock(); } else { System. out.printin(Thread.currentThread().getName()+" Unable To Get Lock ‘and Hence Performing Alternative Operations"); } } ) classReentrantLockDemo { public static void main(String args{]) { MyThread t1 = new MyThread("First Thread"); MyThread t2 = new MyThread("Second Thread”); tstart(); t2start(); } ) 2 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements importjava.util.concurrent.TimeUnit; importjava.util.concurrent.locks.ReentrantLock; classMy Thread extends Thread { staticReentrantLock |= new ReentrantLock(); MyThread{ string name) { super(name); } Public void run() { dof tyt if(.tryLock(1000, TimeUnit. MILLISECONDS) { SOP(Thread,currentThread{).getNamo()+"~-—-— Got Lock"); Thread sleep(5000); LLuntock(); SOP(Thread.currentThreadl).getName()+" break; - Releases Lock") } else { OP(Thread.currentThreadl).getName()+"---~- Unable To Get Lock And Will Try Again"); ) } catch(InterruptedException e) {) y while(true); } } classReentrantLockDemo { public static void main(String argsf}) { MyThread tt = new MyThread("First Threa MyThread t2 = new MyThread("Second Thread”); tHstart(); ‘t2start(); First Thread Got Lock Second Thread~-~-- Unable To Get Lock And Will Try Again Unable To Get Lock And Will Try Again inable To Got Lock And Will Try Again inable To Get Lock And Will Try Again Second Thread~---- Got Lock First Thread——-- Releases Lock Second Thread—~-- Reloases Lock 3 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements + Creating a New Thread for Every Job May Create Performance and Memory Problems. To Overcome this we should go for Thread Pool Concept. Thread Pool is a Pool of Already Created Threads Ready to do Our Job. Java 1.5 Version Introduces Thread Pool Framework to Implement Thread Pools. Thread Pool Framework is Also Known as Executor Framework. We can Create a Thread Pool as follows ExecutorService service = Executors.newFixedThreadPool(3);//Our Choice © We can Submit a Runnable Job by using submit(), service.submit(job); © We can ShutdownExecutiorService by using shutdown(). service.shutdownds importjava.uti.concurrent.Executorservie Importjava.util.concurrent.Executors; classPrintJob implements Runnable { string name; Printiob(String name) { this,name = nam ) public void run(){ SOP(name+"....ob Started By Thread:" +Thread.currentThread().getName()); ty{ Thread.sleep(10000); d catch (InterruptedException e) {) sOP(name+....Job Completed By Thread" +Thread.currentThread().getName()}; ) } class ExecutorDemo { public static void main(String] args) { Printiob] jobs = { newPrintlob("Durga"), newPrintlob("Ravi"), newPrintlob("Nagendra"), newPrintlob("Varma") k ExecutorService service = Executors.newFixedThreadPool(3); for (PrintJob job : jobs) { service,submit(job); } service.shutdown(); } } 9d | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Durga...J0b Started By Thread:pool-1-thread-1 Ravi..Job Started By Thread:pool-1-thread-2 Nagondra...,Job Started By Thread:pool-1-thread-3 Ravi...Job Completed By Thread:pool-1-thread-2 Pavan...lob Started By Threadt:pool-t-thread-2 Durga...ob Completed By Thread:pool-1-thread-1 Bhaskar....Job Started By Thread:pool-t-thread-1 Nagendra....lob Completed By Thread:pool-t-thread-3 Varma....Job Started By Thread:pool-t-thread-3 Pavan....ob Completed By Threac:pool-1-thread-2 Bhaskar....Job Completed By Thread:pool-t-thread-1 Varma....Job Completed By Thread:pool-1-thread-3 On the Above Program 3 Threads are Responsible to Execute 6 Jobs. So that a Single Thread can be reused for Multiple Jobs. Note: Usually we can Use ThreadPool Concept to Implement Servers (Web Servers And ‘Application Servers). PE Ua CS In the Case of Runnable Job Thread won't Return anything. Ifa Thread is required to Return Some Result after Execution then we should go for Callable. Callable Interface contains Only One Method public Object call() throws Exception. If we Submit Callable Object to Executor then the Framework Returns an Object of Type java.util. concurrent. Future © The Future Object can be Used to Retrieve the Result from Callable Job. 55 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements Importjava.util.concurrent.Callable; Importjava.utl.concurrent.Executorservice; Importjava.util.concurrent.Executors; importjava.util.concurrent.Future; classMyCallable implements Callable { intnum; ‘MyCallable(intnum) { ‘his,num = num; } Public Object call() throws Exception { num; i+#){ ums return sum; } classCallableFutureDemo { public static void main(String argsf}) throws Exception { MyCallable[] jobs = { newMyCallable( 10), newMyCallable(20), newMyCallablet 30), newMyCallable(40), newMyCallable(50), newMyCallable(60) k ExecutorService service = Executors.newFixedThreadPool3); for(MyCallable job : jobs) { Future f= service submit(job); system.out.printin(.get(); } service. shutdown(); 6 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad - 500038, ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements FAQ’S 1) What Is Multi Tasking? 2) What Is Multi ThreadingAnd Explain Its Applicat 3) What Is Advantage Of Multi Threading? 4) When Compared With C++ What Is The Advantage In Java With Respect To Multi Threading? 5) In How Many Ways We Can Define A Thread? 6) Among Extending Thread And Implementing Runnable Which Approach Is Recommended? 7) Difference Between tstart() And t.run()? 8) Explain About Thread Scheduler? 9) If We Are Not Overriding run) What Will Happen? 10) Is It Possible Overloading Of run()? 11)Is It Possible To Override a start() And What Will Happen? 12) Explain Life Cycle Of A Thread? 13) What Is The Importance Of Thread Class start)? 14) After Starting A Threa Will Happen? If We Try To Restart The Same Thread Once Again What 15) Explain Thread Class Constructors? 16) How To Get And Set Name Of A Thread? 17) Who Uses Thread Priorities? 18) Default Priority For Main Thread? 19) Once We Create A New Thread What Is Its Priority? 97 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderaba ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements 20) How To Get Priority From Thread And Set Priority To A Thread? 21) If We Are Trying To Set Priority Of Thread As 100, What Will Happen? 22) If 2 Threads Having Different Priority Then Which Thread Will Get Chance First For Execution? 23)If 2 Threads Having Same Pr Execution? rity Then Which Thread Will Get Chance First For 24) How We Can Prevent Thread From Execution? 25) What Is yield) And Explain Its Purpose? 26) Is Join Is Overloaded? 27) Purpose Of sleep()? 28) What Is synchronized Key Word? Explain Its Advantages And Disadvantages? 29) What Is Object Lock And When It Is Required? 30) What Is A Clays Level Lock When It Is Required? 31) While A Thread Executing Any Synchronized Method On The Given Object Is It Possible To Execute Remaining Synchronized Methods On The Same Object Simultaneously By Other Thread? 32) Difference Between Synchronized Method And Static Synchronized Method? 33) Advantages Of Synchronized Block Over Synchronized Method? 34) What Is Synchronized Statement? 35) How 2 Threads Will Communicate With Each Other? 36) wait(, notify(), notifyANQ Are Available In Which Class? 37) Why wait(), notify), notifyAI() Methods Are Defined In Object Instead Of Thread Class? 38) Without Having The Lock Is It Possible To Call wait)? 39) If A Waiting Thread Gets Notification Then It Will Enter Into Which State? 40)In Which Methods Thread Can Release Lock? 41) Explain wait), notify and notifyAll? 8 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderaba ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott comCore Java with SCJP/ OCJP Notes By Durga Sir Multi Threading Enhancements 42) Difference Between notify() and notifyANQ? 43) Once A Thread Gives Notification Then Which Waiting Thread Will Get A Chance? 44) How A Thread Can Interrupt Another Thread? 45) What Is Deadlock? Is It Possible To Resolve Deadlock Situation? 46) Which Keyword Causes Deadlock Situation? 47) How We Can Stop A Thread Explicitly? 48) Explain About suspend() And resume()? 49) What Is Starvation And Explain Difference Between Deadlock and Starvation? 50) What Is Race Condition? 51) What Is Daemon Thread? Give An Example Purpose Of Daemon Thread? 52) How We Can Check Daemon Nature Of A Thread? Is It Possible To Change Daemon Nature Of A Thread? Is Main Thread Daemon OR Non-Daemon? 53) Explain About ThreadGroup? 54) What Is ThreadLocal? 9 | DURGASOFT, # 202.2" Floor HUDA Waitrivanam,Ameerpet, Hyderabad ‘© 040 ~ 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasott com
You might also like
Default Methods in Java 8 - Shaikh
PDF
No ratings yet
Default Methods in Java 8 - Shaikh
3 pages
Delegation of Taxation Power
PDF
No ratings yet
Delegation of Taxation Power
6 pages
9-Article Text-21-4-10-20240829
PDF
No ratings yet
9-Article Text-21-4-10-20240829
11 pages
Lambdas and Functional Interfaces in Java 8 - Shaikh
PDF
No ratings yet
Lambdas and Functional Interfaces in Java 8 - Shaikh
2 pages
Title - Overview of Java 8 Features - Shaikh
PDF
No ratings yet
Title - Overview of Java 8 Features - Shaikh
2 pages
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6458)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (643)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (1005)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (650)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4.5/5 (1856)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (141)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1175)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (582)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (464)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (5181)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (298)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (629)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (2016)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4.5/5 (4103)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4.5/5 (1139)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (144)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2289)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (943)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (1022)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M.L. Stedman
4.5/5 (815)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2814)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (836)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (244)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (903)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1090)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1267)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (2885)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
4/5 (278)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (280)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4135)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (233)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4372)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (2033)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (78)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2546)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (919)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2133)
Little Women
From Everand
Little Women
Louisa May Alcott
4.5/5 (2369)