You are on page 1of 20
Java Threads A thread is @ thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. This hancs-on lab takes you through the basics of using Java threading Resources + Threads section of Java tutorial + Thread dump analyzer 2.0 from java.net Exercises Exercise 1: Extending Thread class Exercise 2: Implementing Runnable interface Exercise 3: ThreadGroup, ThreadPriority, View all threads. Exercise 4: Synchronization Exercise S: Inter-thread communication Exercise 6: Timer and Timerrask 2 Homework Exercise 1: Extending Thread class In this exercise, you are going to learn how to create and start a thread execution by writing a class that extends Thread class. You will learn how to start the thread by either not having the start() method in the constructor of te subclass or having itin the eanstructor of the subclass, 1. The start() method is NOT in the constructor of the subclass 2 The start() method is in the constructor of the subclass (4.1) The start) method is NOT inthe constructor ofthe subclass. (0. Start NetBeans IDE if you have not done so yet. 4, Create a new NetBeans project + ‘Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears + Uncer Choose Project pane, select Java under Categories and Java Application under Projects. Click Next. Under Name and Location pane, for the Profect Name file, type in ExtendThreadClassTest0 as project name, + For Create Main Class fla, type in ExtendThreadClassTest0.. (Figure-1-10 below) + Glick Finish, Ceo steps Name and Location 1 hem Frojct Pojettiine EseraivexiSassTes 5 23. Wome and Location PEE yeeros ProjectFcker: [E\mpavaprajecmenenat sad iaeereet Use Dedicated Fotier for storing Libraries Po re Different users ard erojets can share the same complain ibrar es (se fel for deta). Liveries Create Msn Class (Ever TrreadClers eet] 7 Setas Main Project — =a ere ora | + Observe that ExtendThreadClassTest0 project appears and IDE generated ExtendThreadClassTest0 Java is displayed in the source editor window of Neteans IDE Figure-1.10; Create a new project 2. Modify the IDE generated ExtendThreadClassTest0 java as shown In Code-1.11 below. Study the code by paying special attention {o the bold fonted parts. Note that the start() is Invoked after the object instance of PrintameThread class Is created. [public class ExtendThreadClassTest0 { public static void main( St ing argst]) £ 11 Create object Instance of a class that Is subclass of Thread class ‘System.out printin( "Creating PrintNameThread object instance"); PrintNameThread pnt = ‘new PrintNameThread("A"); 1/ Start the thread by invoking start() method ‘Syster.out,pintin("Caling start() method of" + prtL.getName() + thread); pntistart(); > > Code-Tair Bxtener adCassTest0 fave 3. Write PrintNameThreadjava as shown in Code-1.12 below. [77 Subclass extends Thread class [public class PrintNameThread extends Thread PritNameThread(String name) { super(name); > 1] Override the run() method of the Thread class. 71 This method gets executed when start() mathod 71 is invoked. Public vold run() ¢ System.out printin("run() method of the * + this.getName() +" thread Is called” ); for {int i= 0; 1< 10; 144) ¢ ‘System. out print(this.getName()); > > > Code-1 12; Pantiamethread fava 4 Build and run the project + Right click ExtendThreadClassTesto project anc select Run. + Observe the result in the Output window. (Figure-1.13 below) (Creating PrintNameThread object instance, [Caling start() method of A thread iun() method of the A thread Is called [RAARAARAAA Figure-1.13: Result of running ExtendThreadClassTest0 application Fie Edt View Newgete Source Relator Run Debug Profile Team Tools Window Help HES OE cm Nf Bb O- Oris |S) Gor 5 Eien | PinteneTived ave =| Wee een B-8-|\Reselresiazleule Oh Souce Patou 5 : GBB eratondaces || 7 . : "| brenstreadc public clase PrintManethread extends Thread { 1B rntoetiven. ioe © printwamernread(sczing mane) ¢ = [B TestLoroes =—_ public void ran) [ Syoten.our-printin(*run() method of the * + this.cettame |) = for (int 1-0; 4. 20; dey) t te Syrtem. out. print (obi getttane (1) u we > SSS [ouput oa 1 | ordetavoutDemo Gun) | SereTreacCaerer9 fr) = Calling seect() mothod of 2 thread a | ll i Bordeaouteno (ur) [win B® | 1a [ns 5. Modify the ExtendThreadClassTest0,fava as sown in Code-1.15 below. The code fragments that need to be added are highlighted in bold and blue-colored font. [public class ExteneThreadClassTest0 { public static vold main(String arasf]) ¢ 1/ Create object instance of a class that is subclass of Thread dass ‘System.out printin("Creating PrintNameThread object instance.."); PrintNameTPread ptt ‘new PrintNameThread("A"); UL Start the thread by invoking start() method ‘System. cut printin("Caling stare() method of " + pnti.getName) + * thread”) patustort()s System.out.printin( "Creating PrintNameThread object instance.."); PrintNameThread pnt2 = ‘new PrintNameThre System.out.printin( "Call pnt2.start(); 19 start() method of " + pnt2.getName() +" thread"); System.out printin( "Creating PrintNameThread object instance, PrintNameThread pnt3 new PrintNameThre System-out-printin( "Call pnt3.start( > thread"); > ‘Code-1.15; Modified ExtendThreadClassTest0 java 6. Bullé and run the project + Right click ExtenaThreadClassTesto project anc select Run. + Observe the result in the Output wincow. (Figure-1.16 below) 7. For your own exercise, modify ExtendThreadClassTest0.Java as following. Build and run the application + Greate and start another thread, + ‘Set the name ofthe thread as "MyOwn® return to top of the exercise (12) Tho star() method Is inthe constructor ofthe subclass 4, Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N), The New Project dialog box appears + Uncer Choose Project pane, select Java under Categories and Java Application under Projects. Click Next. + Under Name and Location pane, for the Project Name file, type in ExtendThreadClassTest2 as project name, ‘+ For Create Main Class field, type in ExtendThreadClassTest2, 2 lick Finish, [Grating PrntWemetivead abject instance {cling star) method ofA thread [resting PontNomertvead object instance. {Caling start) method of 8 threse [AAAAAAAAAACresting riniameThreed objec instonce. [scaling start() methos of ¢ thread lssbanesaaccccceccce Figure-i-16: Resul fie Edt Vew Nergne Source Reletor Run Debug Profle Team Took: Window Hep HRS SES com 7 Wd H-@- Qeiseocn ce ] [4s [fee seve sme EAieteeliee eine =] IT a B-8-|ReeRlresiazies|es © (ib source Pazoose 1 GB séefaitosdace> || 2 pupaic clase RxtendThreadClassTests { B Bitencttrendcte: ‘a BB Piwemetirent 3] te sspiie svavie void maun(string axes. OB TestPacoges ie SRE ESET f o.. ‘ sevenscuegetnrin(‘cessise eisuiaatnssas icee soot s € ‘new PrantNameThread ("" : uw 2 a oe ® Senne Syoten.cus.printin ("Calling stars () mechod of " + pntl.geet Ba Preetienet pntt.starei)s u oI rextradaaee a oB Utraes ts iySten. cit peineid ("Ceesting Peintmmettisead object instane © (B resttbrance a8 PrintYemeThread pre? = e new PrintNeneThcend (*D") : 5 Syaten.cut.princin ("calling stars (| aechod of * + pac?.gecx a paca.acarti)? 2 | Syaten.cur.prancan ("czeating Pesniilanetaesas cbsecr snerane © “ 2 J , Output ox > aiCessTesit fur) = | Ww. = Grasting Princianethcesd objecr inevaR Calling seect() method of A thread 1a [ne + Observe thet ExtendThreadClassTest2 project appears and IDE generated ExtendThreadClassTest2, java is displayed in the Source editor window of NetBeans IDF 2. Modify the IDE generated ExtendThreadClassTest2.java as shown In Code-1.21 below. [public class ExteneThreadClassTest2 { public static void main(String argsf]) € PrintNameThread ptt = ‘new PeintNameThread("A"}; brintNamethread pnt2 = ‘new PrintNiameThread("8"); PrintwameThread pnt3 ‘new PrintNamenread("C"); > > (Code-1-21 ErtendThreadClassTest2 Jave method of the PrintNameThread class 43. Write PrintNameThread java as shown in Code-1.22 below. Note that the start{) method is invoked as part of the constructor [public class PrintNameThread extends Thread { PrintNameThread(String name) { super(name) 7/ startQ) method is inside the constructor of the subclass eal public vold runt) « ‘String name ~ getName() for {int i= 0; | < 10; 14) ¢ ‘System.out print{name); > > > ‘Coda-1.2a; PrintNameThread jave 4. Bulld and run the project + Right click ExtendThreadClassTest2 project anc select Run. * Observe the result in the Output wincow. (Figure-1.23 below) [Daaannanansnanpansancccececece Figure-I.25: Result of uring EatendTareaaClssTes2 opaication File Feit View Newgete Source Relator Run Debug Profile Team Tools Window Help HES OE cm Hf BD O- Qrisscneri | Ge ire |: PrntioneToread| joa ati} ExterdTrreadCiessTestt.javn 3 Weel} ‘iencrreacceseeem fa.s«*d © UB Seucefosaoee GG aeratpsdace> 1 erent 2° public clase ExtenaTnreadciassTestt { [B Prntiometireads)| Bs crgeenseonscressimingriceg acy f UB TestPacoges ie Ret eeeD pd putea : (5 cera package By exencrreadcte EB mnaunetivesd sestPacacee a Systen.out.printin ("Calling stars () method of " + pnti.getl) 2 pntt.starei)s u u Systen.cut.printia(*Creating PrintlaneThresd object insta: Pa pew PrintNeneThrend ("5"): n System. out.peinean(*caliing sta: Fa para.ecarc i)? echod of " + prez geet SB esata 2 System. our.prantan ("creating PrintNaneThress object instanc ~ a) , att on rel DP sn Rordetnyouteno far) nes SB) | 13 (INS 5. For your own exercise, modify ExtendThreadClassTest2.java as following. Build and run the application + Create and start another thread, + ‘Set the name ofthe thread as "MyOwn return to top of the exercise ‘Summary In this exercise, you have learned how to create and start a thread by extending Thread class return to the top Exercise implement Runnable interface In this exercise, you are going to create and start a thvead by writing a class that Implements Runnable interface. 1. Create and start a thread by implementing Runnable interface - start() method Is not in the constructor by implementing Runnable interface - start() method is in the constructor (2:1) Create and start a thread by implementing Runnable interface - star() method is notin the constructor 1. Create a new NetBeans project + Select Flle->New Project (Ctrl4Shift+N). The New Project dialog box appears. + Under Choose Project pane, select Java under Categories ond Java Application under Pr 1 click Next + Uncer Name and Location pane, for the Project Name file, type in RunnableThreadTestt as project name, * For Create Main Class field, type in RunnableThreadTest1, + Click Finish + Observe that RunnableThreadTestt project appears and IDE generated RunnableThreadTestt java is displayed inthe source ‘editor window of NetBeans IDE, 2, Modify the 1DE generated RunnableThreadTest1 java 2s shown in Code-2.11 below. Study the code by paying special attention to the bold fonted parts. Note that the start() method neads to be invoked explicty after an object instance of the PrintNameRunnable class's created. [public class RunnablethreadTestt ¢ public static void main(String argstl) { PrintNameRunnable prt = new PrintNameRunnable("A"); Thread ti = new Thread(ont1); thistart(); PrintNameRunnable pnt2 = new PrintNameRunnable("8"); Thread (2 = new Thread(ont2); e2astart(; PrintameRunnable pnt3 = new PrintNameRunnable("C"); ‘Thread 2 = new Thread(ont3); t3.start(); > > Code-Z.A1r RunnablethreadTesti.java 3. Write PrintNameRunnable,java as shown in Code-2.12 below. [7/The cass implements Runnable interface class PrintNameRunnable implements Runnable { String name; PrintNameRunnable(String name) { thisiname = name; > 11 Implementation ofthe runt) defined in the U1 Ronnadle interface, public void runt) { for {int i= 0; F< 10; 14) ¢ ‘System. out print(name); > > > Code-2 Ad; PantameRunnable java 4 Bulld and run the project + Right cick RunnableThreadTest1 project anc select Run. * Observe the result in the Output window. (Figure-2.13 below) [RCBACBACBACBACABCABCABCABCABCE Figare-2.13; Result of running RunnableThvesdTesti application 5. For your own exercise, do the following. Bulld and run the application + Create anther class called MyOwnRunnableClass that implements Runnable interface + MyownRunnableCiass displays values 1 to 10 inside ts run() method + Modify RunnableThreadTesti.java to start 2 thread instances of MyOwnRunnableClass. return to top of the exercise inthe constructor (2.2) Create and start a thread by implementing Runnable interface - start!) method 4, Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Profact dialog box appears 1 Uncer Choose Project pane, select Java under Categories snd Java Application under Projects, 1 Click Next. + Under Name and Location pane, for the Projact Name file, type in RunnabloThreadTest2 as project name, + For Create Main Class field, type in RunnablethreadTest2, Click Finish + Observe that RunnableThreadTest2 project appears and IDE generated RunnableThreadTest2.Java is displayed inthe source ‘editor window of NetBeans IDE, 2. Modify the IDE generated RunnableThreadTest2.java as shown In Code-?.21 below. Stuey the cade by paying special attention to the bold fonted parts [public class RunnableThreadTest2 ¢ public static void main(St ing arast]) € 1/ Since the constructor of the PrintNameRunnable 17 object creates a Thread object and starts it, 77 there is no need to do it here. new PrintNameRunnable("A"); ‘new PrintNameRunnable("S"); ‘new PrintNameRunnable(°C"): > » Code-2 21; RunnablethreadTest java 3. Write PrintWameRunnable java as shown in Code-2.22 below. Study the code by paying special attention Note that the star() method Is inthe constructor ofthe PrintNameRunnable cass the bold fonted parts. [7 The dass implements Runnable interface (class PrintNameRunnable implements Runnable { Thread thread; PrintNameRunnable(String name) { ‘thread = new Thread(this, name}; thread.start(); > 11 mplementation of the run() defined in the 11 Runnable interface. public vold rung) € ‘String name ~ thread.getName(); for {int i= 0; |< 10; it) ¢ ‘System. out print(name) > > > Code-2 22: PantameRunnable java 4 Bulld and run the project + Right cick RunnableThreadTest2 project anc select Run. * Observe the result in the Output window. (Figure-1.23 below) [RBCABCABCABCABCABCABCBACBACBAC Figure-2,23 Result of running RunnableThreadTest2 application return to top of the exercise ‘Summary In this exercise, you have learned how to create a clas that implements Runnable interface and starts a threac. return to the top Exercise 3: ThreadsGroup, View all threads, ThreadPriority In this exercise, you are going to leatn how to display inform non a ThreadGroup, how to set a thread priority, and so on. 3. Set thread priority (2.1) Display threads of a ThreadGroup Create a new NetBeans project + Select File->New Project (Ctrl4 Shift+N). The New Project dialog box appears. + Under Choose Project pane, select Java under Categories and Java Applieation under Projects 1 click Next + Under Name and Location pane, for the Project Name file, type in ThreadGroupTest as project name. ‘+ For Greate Main Class field, type in ThreadGroupTest, Click Finish + Observe that ThreadGroupTest project appears and IDE generated ThreadGroupTest.java is displayed in the source ecitor ‘window of NetBeans IDE. 2. Modify the IDE generated ThreadGroupTest.java as shown in Code-3.11 below. Study the cade by paying special attention to the bold fonted parts [public case ThreadGroupTest ( public static void main (Stringl I args) < 1/ Start three threads first. They should belong 17 to a same Threadscrou ew SimpleThread("Boston”).start(); new SimpleThread("New York").start(); new SimpleThread("Seoul”)-start();, 1/ Get ThreadGroup of the current thread and display 7/ the number of active threads that belong fo the 17 ThreadGroup. ‘ThreadGroup group = Thread.currentThread()-getThreadGroup(); ‘System.out printin("Number of active treads in this thread group * group-activecount();, 1/ Display the names of the threads in the current 11 ThreadGroup. Threadl) tarray = new Thread{ 10}; Int actualsize = group.enumerate(tarray); for {int is0; ' > Code-3.11 ThreadGroupTest java 3. Write SimpleThread.java as shown in Code-3.12 below. [public class SimpreThvead ext nds Thread { public SimpleThread{String st) < super(st); > public void runt) { for (int i= 0; =< 5; I+) ¢ 11 System. out formati"9ed *%s%n*, |, getName()); ty sleep{(tong)(Math.random() * 1000)); > eaten (Interruptedtxception e) 0 > ‘System. out format("DONE! %stén", getName()); > > Code-3.12: SimpieThread ave 4, Build and run the project + Right click ThreadGroupTest project and select Run. + Observe the result in the Output wincow. (Figure-3.13 below) [Number of active threads inthis thread group = # "Thread main In tread greup main ‘Thread Boston in tread group main Thread New York in thread group main Thread Seoul in thread group main lboNe! Seout [DONE! New York IDONE! Boston Figure-3.13 Result of running ThreadGroupTest application return to top of the exercise 5. Fer your own exercise, do the following. Sulld ané run the application ‘+ Mogity ThreadGroupTest java to cate another (4th) SimpleThread instance using your capital city of your country (8.2) Display all threads inthe system 1. Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears. + Uncer Choose Project pane, select Java under Categories and Java Application under Profects Click Next + Under Name and Location pane, for the Projact Name file, type in DisplayAliThreads as project name. + For Create Main Class filo, type In Displayallthreads. Click Finish + Observe that DisplayAllThreads project appears and IDE generated DisplayAllThreads.java is displayed in the source ecitor window of NetBeans IDE. 2. Modify the IDE generated Displays bold fonted parts WThreads.java as shown in Code-3.21 below. Study the code by paying special attention to the [public lass DisplayalThreads ( public static void main(String{] aros) { 1 Start three threads fist. They should belong {to a same ThreaesGroup. ‘new SimpleTaread( "Boston. start) new SimpleTnread( "New York") star(); new SimpleTaread( Seoul) stare(); Tm it) tarray = findAltThreads(): for {int i=0; ictarray.lengtryi++)¢ ‘System. cut printin("Threae * + tarrayl].getName() + in thread group " + taray[i]. getTheadGroup().getName()); > > U1 Create an array of al threads in the system. Public static Thread[] findAliThreads() ¢ ‘ThreadGroup group = Thread.currentThread{).getThreadGroup(); ‘ThreadGroup topGroup = group; while (group t= null) topGroup = group; ‘group = group.getParent(); > Int estimatedsize = topGroup.activeCount() * 2; Thread{] slackList = new Thread[estimatedsize]; Int actualSize = topGroup.enumerate(siackList); ‘Thread{] list = new ThreadfactualSize]; System-arraycopy(slackList, 0, list, 0, actual return Ii > t > Code-3.21: DisplayAlThreads java 3. Write Simplethread.java a shown in Code-3.22 below. [public class SimpleThvead ext nds Thread { public Simplethread{String st) < super(str); public void runt) ¢ for {int i= 0; 1 < 5; i++) € 1/ System.outformati"9éd Ss%n", i, getName()); we sleep{(tong)(Math.random() * 1009)); > eaten (Interruptedéxception e) (> > System.outsformat("DONE! %sX%n", getName()); > > Code-3.22: SimpleThread java 4 Bulld and run the project + Right click DisplayAllThreads project and select Run. + Observe the result in the Output wincow. (Figure-3.23 below) [Thread Reference Handler in thread group system [Thread Finalizer in thread group system Thread Signal Dispatcher In thread group system {Thread main in tread group main "Thread Boston in tieaa group main Thread New York in thread group main Thread Seoul in thread group main IDONE! New Yor loone! seout IDONE! Boston Figure-1.23 Result of running DisplayAllThreads application 5. Fer your ewn exercise, do the following, Build and run the application ‘+ Mogity DisplayAllThreads.java to create another (4th) SimplaThread instance using your capital cy of your county, return to top of the exercise (3.3) Sot thread priority Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears 1 Uncer Choose Project pane, selec Java under Categories and Java Application under Projects Glick Next. + Under Name and Location pane, for the Project Name fielé, type in ThreadsPriority as project name. + For Create Main Class field, type In ThreadsPriority, Click Finish + Observe that ThreadsPriority project appears and IDE generated ThreadsPriority.java is displayed in the source editor window of NetBeans 1D. 2, Modify the IDE generated ThreadsPriority.java as shown in Code-3.31 below. Study the code by paying special attention to the bola fonted parts, [public dass ThreadsPronty ( public static void main(String] args) { Thread ti = new SimpleThread("Boston") ustant() 1/ Set the thread priority to 10(highest) eLsetPriority(10); Thread 12 = new SimpleThread("New York"); wstar(); // Set the thread priority to 5 AB. setPriority(5); Thread t3 = new SimpleThresd("Seou!"); eastanO; 11 Set the thread priority to 1 8B setPriority(1); > > Code-3.31" ThreadsPrioriy.jave 3. Write SimpleThread.java as shown in Code-3.32 below. [public dass SimpleThvead extends Thread { public SimpleThread{String st) < super(st); > public void runt) { for {int |= 0; 10; 14) ¢ ‘Systerout printin(' + "* + getName() ++" Prorty = "+ getPrionty()}: > System.outiprintin‘Done! " + getName); > > Code-3.32: SimpleThread java 4 Build and run the project + Right click ThreadsPriority project and select Run. * Observe the result in the Output window. (Figure-3.33 below) (0 Boston Prionty = 10 [0 Seou! Priority = 1 lo New York Priory = 1 Boston Priority = 10, 1 Seoul Priority 1 New York Picrity = 12 Boston Priority = 10 2 Seoul Priority [3 Boston Prionty = 10 12 New York Priority = § '4 Boston Prionty = 10 [3 New York Prionty = 5 '5 Boston Prionty = 10 16 Boston Prionty = 10 17 Boston Priority = 10 '8 Boston Prionty = 10 19 Boston Priority = 10 Done! Boston la New York Priority [5 New York Priority [6 New York Priority 17 New York Priority = § [8 New York Priority '9 New York Priority [Done! New Yore 13 Seoul Priority '4 Seoul Priority '5 Seoul Prianty [6 Seoul Priority = 1 17 Seoul Priority = 1 13 Seoul priority = 1 '9 Seoul Priority [Donel Seoul Figure-3.33; Result of running ThreadsPrionty application return to top of the exercise ‘Summary In this exerelse, you have learned how to retrieve information on a ThreadGroup. return to the top Exercise 4: Synchronization In this exercise, you are going to exercise how to do synchronization among threads 1, Build and run a program in which threads are NOT synchronized 2 Build an run a program in which threads are synchronized through synchronized method 3. Bulld and run a program in which threads are synchronized through synchronized statement on a common object, (4.1) Build and run a program in which threads are NOT synchronized In this step, you are going to build an application that displays & result that isnot desirable since threads are not synchronized, 4, Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears + Uncer Choose Project pane, select Java under Categories and Java Application under Projects. Click Next. + Under Name and Location pane, for the Pr + For Create Main Class field, type In Unsyn: + Glick Finish, sct Name file, type in UnsynchronizedExample as project name. ronizedExample. + Observe that UnsynehronizedExample project appears and IDE generated UnsynchronizedExample.java is displayed in the Source editor window of NetBeans IDE 2, Modify the IDE generated UnsynchronizedExample.java as shown in Cade-4.11 below, [public class UnsynehronizedExample { public static void main(Stringt] args) £ ‘ew PrintstringsThread{"Hello %, “theres; ‘new PrintStrinasThread{"How are *, “you?"); ‘ew PrintstringsThread("Thark you ", "very much"); > » ‘Code-4. 11 Unsynenronizedexarple Jove 3. Write PrintstringsThreae: java as shown in Code-4.12 below. [public class printStringsThread implements Runnable { “Thread thread Sting str, str2; PrintStringsTaread(Strng str, String st-2) { this thread = new Thread(this); thread.start(); > public void runt) { TwoStrings.printstrl, str2); > > Code-a,12: PrintStringsThread jave 13 below. Study the code by paying special attention to the bolé fonted part 4, Write TwoStrings,java as shown In Code~ Note that the print methed ls nt synchronized [public clase TwoStangs { 11 This method is not synchronized static void print(String stri, String str2) { ‘system.out print(strl}: tye Thread. steep(500); 4 eaten (Interruptedtxception ie) { > System.out printn(st2); > > Code-#.i3i TwoStrings:jave 5. Build and run the project + Right click Unsynchronizedexample project and select Run, + Observe the result n the Output wincow. (Figure-4.14 below} Fielio How are Thank you there. \very much! you? Figure-4. 14; Result of running UnsynchronizedExample application return to top of the exercise (4.2) Build and run a program in which threads are synchronized through synchronized method In this step, you are going to buld an application that displays a desired result because the threads are synchronized, Create @ new NetBeans project + Select Flle->New Project (Ctrl+Shift+N). The New Project dialog box appears. * Under Choose Project pane, select Java under Categories and Java Application under Projects click Next. {+ Uncer Name and Location pane, for the Project Name file, type in SynchronizedExamplei as project name, + For Create Main Class field, type in SynchronizedExampled, 1 click Finish + Observe that SynchronizedExamplel project appears and IDE generated SynchronizedExamplet.java is displayed in source editor window of NetSeans IDE 2, Modify the IDE generated SynchronizedExamplet.java as shown In Code-4,21 below, [public dass SyachronizedExamplei < public static vold main(String] args) { ‘ew PritStringsThread("Hella, "there."}; ‘ew PrintstringsThread( "How are ", "you?" new PrintStringsThread("Thank you *, "very much > > Code-4.21: SynchronizedExampleljave 53. Write PrntStringsThreac:jave as shown In Code-4.22 below. [public class PrintStringsThread implements Runnable { Thread threads Sting str, st2; PrintStringsTaread{Strng str, String st-2) { this.strl = st; this.st2 = str2j thread = new Thread(this); thread. start); , public vold ran) ¢ “TwoStrings print(strt, st2); > > Code-4.22: PrntstringsThread java 4. Write TwoStrings.java as shown in Code-4.23 below. Study the code by paying special attention to the bold fonted parts [public case TwoStrings ¢ 11 This method is now synchronized ‘Synchronized static old print(Sting str, String st72) ¢ ‘System. cut print(strt); tw Thread sleep(500); 2 eateh (InterruptedException ie) { > System.out printn(str2); > > (Code-4.25; TwoStrings ave 5, Build and run the project + Right click Synchronizedxamplet project and select Run. + Observe the result in the Output winow. (Figure-4.24 below) [How are your Trani you vary much! Hella vere Figure-4.24 Result of running UnSynchronizedexamplel application return to top of the exercise (4.3) Build and run a program in which threads are synchronized through synchronized statement on common object In this step, you are going to buld ancther application that displays @ desired result because the threads are synchronized. 4, Create a new NetBeans project + Select File->New Project (Ctrl#Shift+N). The New Project dialog box appears Uncer Choose Project pane, select Java under Categories and Java Application under Projects. Click Next. + Under Name and Location pane, for the Projact Name fielé, type in SynchronizedExample2 as project name, ‘+ For Create Main Class field, type in SynchronizedExample2. 2 Glick Finish, + Observe that SynchronizedExample2 project appears and IDE generated SynchronizedExample?.java is displayed in the Source ecitor window of NetBeans IDE 2, Modify the IDE generated SynchronizedExample2.java as shown in Code-4.21 below. [pubic clas Syachronizedxarsple? { public static void main(Stringt] args) { Twostrings ts = new Twostrings(); ‘ew PrntstringsThread( ‘Hello *, "here. ts) ‘ew PrintstringsThread{"How are °, "you", 3); ‘ew PrintstringsThread("Thank you", "very much! ts}; > (Code-4,31 Synehron zedExample2, Jove 3. Write PrintstringsThreae.java as shown In Code~4.32 below. Study the code by paying special attention to the bold fonted parts. [public class PrntstringsThvead Implements Runnable < ‘Thread thread String str, str2; Twostrings ts; PrintstringsThread(String trl, String str2, “Twostrings ts) ¢ this.strl = stray thisstr2 = st2) this ts = ts, thread = new Thread(this); thread. start); , public vold run) « 7/ Synchronize over TwoString object ‘synchronized (ts) { ‘ts.print(strd, str2); > > (Code-4.32; PrntStrngsThread java 4. Write TwoStrings.java as shown in Code-4.33 below. [public clase TwoStrngs < state voléprit(String ser, String st2) < ‘Systern.out printstel); we "Thread sleep(500); } catch (inerruptedException i) < > System.out;printin(str2); > > Code-4.35; TwoStangs eve 5. Bulld and run the project + Right click SynchronizedExample2 project and select Run. * Observe the result in the Output window. (Figure-4.34 below) [How are you? [Thank you very mucht Hela tere Figare-4.34; Result of running UnSynchronizedExample2 application Summary In this exercise, you have learned how to use synchronization Exercise 5: Inter-thread communication (6.1) Producer-Consumer without inter-thread communication 1, Create a new Net@eans project + Select Fi + Click Next return to top of the exercise return to the top >New Project (Ctrl4Shift+N). The New Project dialog box appears. + Under Choose Project pane, select Java under Categories ond Java Application under Pr + Under Name and Location pane, for the Project Name “ele, type in ProducerConsumerUnsynchronized as project name. * For Create Main Class field, tyoe in ProducerConsumerUnsynehronized, + Click Finish. + Observe that ProducerConsumerUnsynchronized project appears and IDE generated ProducerConsumerUnsynchronized.java Is displayed in the source editor window of NetBeans IDE, 2. Modify the IDE generated PraducerConsumerUnsynchronized.java as shown in Code-5.11 below. [public class ProducerConsumerUnsynchronized { public static vold main(Stringt} ares) { cubdyHote ‘new CubbyHote(); Producer pi = new Producer(c, 1); Consumer ci = new Consumer(e, 3); plstan(; cuman0y ode-S.11r ProducerConsumerUnaynvronized java 3. Write CubbyHole.java as shown in Code-5,12 below. Study the code by paying special attention to the bold fonted parts [77 Unsynchronized CubbyHole. "7 '7/ Results are unpredictable; a number may be read before a number has '7/ been produced or multiple numbers may be produced with only one or 171 two being read adding synchronization ensures that a number Is first 171 produced, then read in the correct order. public class CubbyHole { private boolean available = false; public int get) ‘available = false; > public void put(int value) { contents = values ‘valle = true > > Code-5.12: Cubbyrole java 4, Write Producer java as shown in Code-5.13 below. [public dass Producer extends Thread < private CubbyHole cubbyhale; brivate Int number: public Producer(CubbyHole , int number) ( ‘ubbyhole = ¢; this number = number; > public void runt) ( for {int |= 0; |< 10; 14+) ¢ cubbyhote put() ‘System.out prntin( "Producer #” We puts +; this.number ww sleep{(ine\(Matn.random() * 100); 4 ate EateruptecEacepton 6) C > > Code ‘Th Producerjave 5. Write Consumer.java as shown in Code-5.14 below. [public class Consumer extends Thread ( CupbyHole cubbyhole; int number; public Consumer{CubbyHle ¢, i ‘eubbyhole = ¢; this.number = number; > public woid runt) { int value = 0; for (int |= 0; | < 10; 144) ¢ value = cubbyhote.get(); ‘System. out printin("Consumer #” + this.number got: "+ value); > > » Code-5 14: Consurerjava 6, Build and run the project + Right click ProducerConsumerUnsynchronized project and selact Run + Observe the result In the Output wincow. (Figure-5.15 below) (Producer #1 put: 0 [consumer #1 got: [Consumer #1 got [Consumer #1 got [Consumer #1 got [Consumer #1 got (consumer #1 got: 0 [Consumer #1 got: 0 (Consumer #1 got: 0 (Consumer #1 got: 0 [Consumer #1 got: 0 IPraducer #1 put: 1 lproducer #1 put: 2 lproducer #1 put: 3 lprocucer #1 put: 4 lproducer #1 put: 5 producer #1 put: 6 lProducer #1 put: 7 lproducer #1 put: 8 Producer #1 put: 9 Figure-5.15; Result of running ProducerConsumerUnsyachronized application return to top of the exercise (6.2) Producer-Consumer with interthread communication 4, Create a new NetBeans project + Select Flle->New Project (Ctrl+Shift+N), The New Project diag box appears 2 Uncer Choose Project pane, select Java under Catagories and Java Application under Projects Click Next. + Under Name and Location pane, (or the Project Name ‘iel6, type in ProducerConsumerSynchronized as project name. + For Create Main Class fila, typc in ProducerconsumerSynchronized, + Click Finish, + Observe that ProducerConsumerSynchronized project appears and IDE generated ProducerConsumerSynchronized.java is displayed inthe source editor window of NetBeans IDE 2. Medify the IDE generated ProducerConsumerSynchronized.java as shown in Code-5.21 below. [public class ProducerConsumerSynchronized ¢ public static void main(String{] ares) { CcubdyHole c = new CubbyHole() Producer pt Consumer new Proaucerte, 1 new Consumert, pista); elstanQ > > Code-S 21; ProducerConsumerSynewonized java 3. Write CubbyHole.java as shown in Code-5.22 below. Study the code by paying special attention tothe bold fonted parts. [public class Cubbyrole ( Private boolean avs public synchronized int get(int who) { false; ‘Syster.out format("Consumer Sed gat: Sdn", whe, contents); notityAll(): > public synchronized void p int who, in value) { while (available == true) < yt wait); > eaten (Interruptedtxception €) evolbie = tue SpremuforatProduce kd pi En wh, content) nouiyali; , b Code-5.22; Cubbyrole java 4. Write Producer java as shown in Coce-5.23 below. [public class Producer extends Thread ¢ private CubbyHole cubbyhole; Drivate int number: public Producer(CubbyHolec, int number) < ceubbyhole = ¢; this number > number; public void run < for {int |= 0; 1< 10; H+) ¢ ‘cubbyhole.put(aumber, I}; wy sleep{tint Math random() * 100)); } eaten (interruptedexception e) { } > , » Code-5.2 Producerjava 5. Write Consum Java as shown in Code-5.24 below. [public class Consumer extends Thread ( Drivate CubbyHole cubbyhale; Drivate int number; public Consumer{CubbyHole c, Int umber) { cubbyhole = ¢; this number = number; > public void ran) < Int value = 0; for {int |= 0; | < 10; 4) ¢ value = cubbyhote.get(rumber); > > > Code-5.24r Consumerjava 6, Build and run the project + Right click ProducerConsumerSynchronized project and select Run, *+ Observe the result in the Output wincow. (Figure-5.25 below) Producer put: 0 [consumer 1 got: 0 Producer 1 put: 2 (consumer 2 got! 1 Producer 1 pur: 2 Iconsumer £ got: 2 Producer 3 put: 3 [consumer 2 got: 3 Producer 3 put: 4 (consumer 2 got: 4 Producer 4 put: 5 [consumer 1 got: 5 Producer 1 put: 6 [consumer 1 got: 6 [Producer 1 put: 7 Iconsumer 2 got: 7 Producer 1 pu: 8 (consumer # got: 8 Producer 3 put: 9 [consumer # got: 9 Figure-5.25; Result of runring PreducerConsumerSynchronized application return to top of the exercise Summary In this exercise, you have learnes how to perform inter-thread communication by the usage of walt), netify(), and notfyAl() methods. return to the top Exercise ‘Timer and TimerTask In this exercise, you wil learn how to use Timer and TimerTask to schedule a single or repeating task: 1. Schedule one-time task 2. Schedule repeating task (6.1) Schedule one-time task 4, Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears. + Under Choose Project pane, select Java under Categories and Java Application under Projects click Next + Under Name and Location pane, for the Project Name fielé, type in TimerReminder as project name. ‘+ For Create Main Class field, tyoe in TimerReminder, 2 Click Finish + Observe that TimerReminder project appears and IDE generated TimerReminder java is cisplayed in the source editor window fof NetBeans IDE, 2, Modify the IDE generated TimerReminder-java 2s shown in Code-6,11 below, Study the code by paying special attention to the bald fonted parts [import java.cti-Timer, Import Jave.utl-TimerTask; je * Simple demo that uses java.uti-Timer to schedule * once 5 seconds have passed. " public lass TimerReminder { Timer timers public TimerReminder(int secones) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); > class RemindTask extends TimerTask ¢ ‘public void run() { ‘System.out printin("Time's up!"); Umer-cancel(); //Terminate the timer thread > > public static void main(String args{l) { ‘System.out print" About to schedule Reminder task in 5 seconds new Timereminder(5); Systemout printin( "Task schedule") > » Code-6.11r TimerReminderjava 3, Bull and run the project + Right click TimerRaminder project and select Run. + Observe the result In the Output window. (Figure-6.12 below) [About to schedule Reminder task in 5 seconde Mask scheduled, {Time's up! Figure-6.12: Result of running UnTimerReminder application return to top of the exercise (62) Schedul repeating task 4, Create a new NetBeans project + Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears + Under Choose Project pane, select Java under Categories and Java Application under Projects, Click Next, + Uncer Name and Location pane, or the Project Name ‘ile, typa in AnnoyingBeep as project name. + For Greate Main Class field, type In AnnoyingBeep. 2 click Finish + Observe that AnnoyingBeep project appears and IDE generated AnnoyingBeep.java is displayed in the source editor window of NetBeans IDE, 2. Modify the IDE generated AnnoyingBeep.Java as shown in Code-6.21 below. Study the cade by paying special attention to the bole [rmportjava.cti-Timer; Import java.utl-TimerTask; import java awe Tealkt, pen ~ Schedule a task that executes once every second. = Beep every second, ” public class AnnoyingBeep { Toolkit toolkit; Timer timer; public AnnoyingBeep() { toolkit = Tookit.getDefaulToolkt); timer = new Timer(); timer schedule(new RemindTask(), 0, /finitial delay 11000); //subsequent rate > class RemindTask extends TimerTask { int numwarningBeeps = 3; public void run() { F (numWarningBeeps > 0) < Hk. beept); ‘System out format numaraingBeeps--; > else ¢ Iki. beep): ‘Systern.out format("Time's up!9én"); Zfeimer cancel(); //Not necessary because we call System exit Systers.ext(0); //Stops the AWT thread (and everything else) epI%6n"); > > > public static void main(String args{]) { ‘Systemoutsformat("About to schedule task.%6n"); new AnnoyingBeep(); System.outformat( "Task scheduled. 860"); > > Code-6 21: AnnoyingBeep java 2 Bulle and run the project + Right cick AnnoyingBeep project and select Run. + Observe the resuft in the Output window. (Figure-6.22 below) [About to schedule tax, Mask scheduled, 'seep! iBeep! Beep! Time's up! Figure-6.22; Resuk return to top of the exercise Summary In this exercise, you have lesrned how to use Timer and TimerTask lasses to schedule one-time or repeating tasks, return to the top Homework 1, The homework is to create a new NetBeans project called MyRunnableProject as folowing, + Create a class called MyCurrentDate that implements Runnable terface. 1 The MyCurrentDate class displays the current date and time 10 times, with 200 mill seconds interval - use sleep() method for this Interval + Create a class callee MyMain, which contans main() m 1d, In which 3 Instances of MyCurrentDate threads are being run,

You might also like