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)
31 views
Java CHP 4 Notes
Uploaded by
Pandurang k Kamble
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java Chp 4 Notes For Later
Download
Save
Save Java Chp 4 Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
31 views
Java CHP 4 Notes
Uploaded by
Pandurang k Kamble
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Java Chp 4 Notes For Later
Carousel Previous
Carousel Next
Save
Save Java Chp 4 Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 47
Search
Fullscreen
a 42 JAVA PROGRAMMING (DIP. gey ty 4 grem ran successflly at its very first attempt. It fs Common to make mina, 7 ly does @ program mm. A mistake might lead to an error causing the Program ty » gram. A mis ig : ‘ake that can make incorrect program. a Java's exception-handling mechanism. An exception is an abnormal developi as well as typing 2 unexpected res This chapter also exami Condi. . In other words, exception is a run-time error. In computer langusge that arises in a code sequence at run ti do not support exception handling, errors must be checked and handled manually. hithreaded Unlike most other computer languages, java provides built in support for multithreade: Programming multithreaded program contain two ‘or more parts that can run concurrently. Each part of such program is calle, thread, and each thread defines a separate path of execution. ERRORS ‘The wrongs or mistakes that can make program go wrong is called as errors, ° Errors may be logical or may be typing mistakes, * An error may produce an erroneous or incorrect ouput or may terminate the execution of the progan abruptly or even may cause the system to crash, * So it is important to detect and manage all error Conditions in the program so that the program wil sa terminate or crash during execution, 4.2.1 TYPES OF ERRORS SL AYPES OF ERRORS : Lt aR Qu. What are different types of errors? 12,14 2M) Errors may broadly classified into two categories : (1) Compile-time errors (2) Run-time errors a) Compile-time errors ; © Allsyntax errors compile time errors, * Whenever the compiler displays an Srror, it will not ereatethe.classfile, It is therefore Recessary that we fix all the errors before we can successfully compile and run the program. Example : Itustration of compile-time errors, /* This program contains an error */ class Error | { Public static void main (String args []) { System.out printin(“Hello java!" V/missings } } eep- Text Book Series 7 JAVA PROGRAMMING (DIP. V SEM. CO.CMIF) he java compiler does a nice job of The jave comple doc ¢ job of telling us where the errors are in the program. ple, if we have missed the semi sed the semicolon at the end of print statement in example, the following For © message Will be displayed on the screen : Error 1. Java: 7: “y'expected System.out.printIn (“Hello Java!”) error We can now go to the appropriate line, correct the crror, and recompile the program. Sometimes a single a may be the source of multiple errors later in the compilation. For example, use of an undeclared variable ‘i il i : in a number of places will cause a series of errors of “undefined variable”. c : adie We should generally consider the earliest errors as the major source of our problem. ‘After we fix such an error, we should recompile the program and look for other errors. Most of the compile-time errors are due to typing mistakes. Typographical errors are hard to find. We may have to check the code word by word, or even character by character. The most common problems are : @ Mi semicolons Gi)Missing (or mismatch of) brackets in classes and methods. (iii) Misspelling of identifiers and keywords. (iv) Missing double quotes in strings. (¥) Use of undeclared variables. (vi) Incompatible types in assignments/ initialization (vii) Bad references to objects. (viii) Use of = in place of == operator and so on. Other errors we may encounter are related to directory paths. An error such as Java C : command not found means that we have not set the path correctly. We must ensure that the path includes the directory where the java executables are stored. fully creating the class file but may not run properly. (2) Run-time errors logic or may terminate due to errors such as stack Sometimes, a program may compile succes + Such programs may produce wrong results due to wrong overflow. common runtime errors are > Dividing an integer by zero. Accessing an element that is out of the bounds of an array. Trying to store a value into an array of an incompatible class or type. iv) Trying to cast an instance of a class to one of its subclasses. ¥) Passing a parameter that is not in a valid range or value for a method. vi) Trying to illegally change the state of a th vil) Attempting to use a negative size for an array. i te 10 access a method or a variable. ill) Using a null object reference as a legitimate object reference X) Connecting invalid string to a number. . ) Accessing a character that is out of bounds of a strin; read.* When such errors are encountered, java typically generates an crror message and aborts the program. Example : Illustration of run-time errors class Error? { Public static void main (String args [}) { inta= 10; int b=5; inte=5; int x= al(b-c); Mivision by zero System.out.printin(“x =" + x); nt y = a(b+c); System.out.printIn(*y =” + y); } } Above program is syntactically correct and therefore does not cause any problem during compilation, However, while executing, it displays the following message and stops without executing further statement. Java.lang. ArithmeticException:/by zero at Error2.main (Error 2,java : 10) When java run-time tries to execute a division by zer0, it generates an error condition, which causes the program to stop after appropriate message. isplaying an 4.3 EXCEPTION $-09 (2M) Q2. What is exception? Give different types of| exception that could occur during runtime. S-12 (6M) <-Wel3 2M) Q.1. What is an exception ? Q.3. Define an exception. Q.4. Mention any: two common Java exception and their cause. 5-13 (2M) 44 | JAVA PROGRAMMING (DIP. V SEM. Co ny * When the j such as dividing an integer by zero, it crey exception object and throws it (i.e. inform that an error has occurred), ferpreter encounters ay, If the exception objects is not caught and hang), properly, the interpreter will display ang, message as shown in the output of example of , time errors and will terminate the program, If we want the program to continue with y. execution of the remaining code, then we sho, tty to catch the exception object thrown by the isplay an appropriate message for taking corrective actions. This task is known as exception handling. The purpose of exception handling mechanism ig to provide a means to detect and report a “exceptional circumstance” so that appropr action can be taken. error condition and then The mechanism suggests incorporation of a separate error handling code that performs the following tasks : (1) _ Find the problem (Hit the exception), 2) Inform that an error has occurred (Throw the exception). @) Receive the exception), error information (catch the (4) Take corrective actions (handle the exception) * The error handling code basically consists of two segments, one to detect error and to throw exceptions and the other to eateh exception take appropriate action, © When writ and to '8 Programs, we must always be ot the lookout for places in the program where an exception could be generated * Some common exception that we must watch out for catching are listed in table 4,3, Exception type “Arithmetic exception, Cause of exception Caused by math errors such as division by zero. « An exception is a condition that is caused by a run time error in the program. ‘ArrayIndexOutOF Caused by bad array BoundException, indexes, [BoundException, | indexes.Book Series 45 Caused when a program tries to store the wrong of data in an array, ‘aused by an att ace! npt to fille, (Caused by referencing a non exister -
javaNested Try 2 Divide by 0 : java.tang.ArithmeticException:/by 2210, Case 3: a=2 C Spjava NestedTry. a=2 ArrayIndexOutOfBound. Nesting of try statements can occur in less obvious ways when methods calls are involved. In this case, the try within the method is still nested inside the outer try block, which ealls the method. Here, is the previous program recorded 50 that the nested try block is moved inside the method nestedtry () Example 2: class Method NestedTry { 49 4.3.6 THROW STATEMENT. JAVA PROGRAMMING (DIP. V SEM. CO,CM.IF) static void nestedtry (int k) UW nestedtry block U1 division by zero int) = (1,2,3,4)5 t(10] = 25; UW generate an out-of-bounds exception } } catch (ArrayIndexOutOfBoundException e) { System.outprintin (“Array index out-of bound” +o); i } public static void main (String args []) { ty { inta=0; int b= 25/5 System.out.printin (“a= "+ a); nestedtry (a); } catch(ArithmeticException e) { z System.out printIn (“Divided by 0” +c); 3 } } fens Qu. Explain the following clause with respect to © exception han ra z 6 throw. 809,13, W12 (IM), » /S:14, W-14 (2M), MSBTE-SOQP (2M)DJ- Text Book Series 410 There may be times when we would like to throw ur own exceptions. We can do this by using the keyword throw as follows : throw new Throwable 'e subclass; For example, throw new ArithmeticException (); throw new NumberFormatException (); The following example demonstrates the use of a user-defined subclass of throwable class. Note that exception is a subclass of throwable and therefore My Exception is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught. Example: import java.lang. Exception; class MyException extends Exception { MyException (String message) { super (message); 3 } class TestMyExeeption { Public static void main (String args{]) { 5, y= 1000; if (2<0.01) { throw new MyException (“Number is small” } a3 catch(MyEXception e) Tc Out.printin (“caught my Exception” 3 a catch (MyException e) AVA PROGRAMMING (DIP. SEM oo System.out.printin (“Caught My exceprig,~* System.out.printin (e.getMessage () ), } finally, { } 3 } (Output : Caught my exception ‘Number is too.small Lam always here Systemout.printin* Tam always here * The object e which contains the error message “Number is too small” is caught by the catcj block which then displays the message using the getMessage () method. Program 1: Write a program to throw a user defined exception as “invalid age” if age entered user is less than eighteen, Reza ‘Ans. class AgeException extends Exception { String s; AgeException (String ss) { } String tostring () return s; } } Public class Example | { public static void main (String args f)) { scanner input = new scanner (System. in); int age; System.out printin“Enter an Age : »; age=input.nextInt (); ” try { —wa ook Series (oir. v SEM, CO.CMIF) oge
10) throw new MyException (a); System.out.printIn(*Normal exit”); a public static void main(String args{ J) { try { ‘compute(1); compute(20); } catch (MyException e) { System.out.printIn(“Caught” +e); } } } This example defines a subclass of Exception called MyException. This subclass is quite simple: it has only a constructor plus an overloaded toString( ) method that displays the value of the exception. The ExceptionDemo class defines a method named compute( ) that throws a MyException object. JAVA PROGRAMMING (DIP. V SEM. CO,CMLIF) rown when compute( )’s 419 ‘The exception is th integer parameter is greater than 10. The main( ) method sets up an exception handler for MyException, then calls compute( ) with a legal value (less than 10) and an illegal one to show both paths through the code ‘Output: Called compute(!) Normal exit Called compute(20) Caught MyException{20] 44 MULTITHREADED PROGRAMMING : Those who are familier with the modern operating system such as Windows 95 and Window XP may recognize that they can execute several programs simultaneously, This ability is known as multitasking in’system’s terminology it is called multithreading. + “Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (Processes), which can be implemented at the same time in parallel. Java programs that we have seen and discussed so far contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runthrough a sequence of execution and finally ends. At any given point of time, there is only one statement under execution. cjass ABC ( tb seginsing +t single threaded body of exceution spend Fig.4.4 (a) Single - threaded program + A thread is similar to program that has a si yw of control. It has a beginning, a body, and an end, and executes commands sequentially. ccc ee Conceptual -aarfte, HACTTAS.by Text Rook Series Ui fact all main pr called single threaded progam, Every program will have at feast one thread as Fig dattay, A unique property of Java nuultith multiple Hows of control in developing, prop its support for Phat i ables us to use Jing, inva Fach flow of control may be thought of asa thread that runs 4.A(b), ns multiple flows of control ite tiny program known in parallel to other is shown in F that con is known as multithreaded progr 4AM(b) shows a ds, one mai n with four The ma ain method fe and start the other three threads, namely A, B and C, module, which is des Mai thread Main method ‘modulo Start Start Start ep ‘Switching ‘Switching Thread A Thread B Thread © Fig 44.) A multithreaded Program Once initiated by the main thread, the thread A, B,C sun concurrently and share the resources jointly. 1 is like people living in joint families and sharing certain resources among all of them, ‘The ability of a language to support multithreads is referred to as concurrency. Since threads in java are subprograms of a main fon program and share the same memory space, they are known as Lightweight threads or Lightweight process. ) Extensively = 7% ANF 1, aarp, ay a) Q) @) (4) important to remember that “threads py. IcI" does not really mean that they eq, Since all the threads are running on ution is shared betyy. or, the flow of exe ids, ‘The Java interpreter handles y. witching, af control between the thread in yg. way that it appears they are running concurren, 5 a powerful prog Multithreading, summing tn) iat makes java distinctly different from its fell, programming languages. Multithreading is useful ina number of ways enables programmers to do multiple things atone time. ‘They can divide a long program into threads and execute them in parallel, ‘Threads are extensively used in Java-cnabled browsers such as not Java, These browsers can download a file to the local computer, display & web page in the window output another web page toa printer and so on, OF MULTITHREAD (OGRAMMING Various benefits of multithreaded programming are : Resource s aring : A thread shares memory and resources by default, ‘The code sharing allows an application to have several thread activites within the same address space. So it is beneficial for memory. Responsiveness: Multithreaded application gives more response to the users. Economy : If we allocate memory and resources for each process then it is costly. But here thread shares resources of the same process, soit becomes economical, Uilisation of multiprocessor architecture : Multithreading increase the usage of multi CPU architecture,DJ wo @ @ @ Text Book Series an . 5 AVA PROGRAMING (O1P.V SEM. CO, 4.4.2 DISADVAL SOF MULTITMREADING: | [yi MING (OHV o.cmsr) - a = (6) | Ithelps in developing | helps in developing | 0 ‘sand debugging is more complex, efficient programs. efficient operating oe a may face race conditions or systems, deadlocks. : _ d : (7) | Tis cost-effective in | Itis expensive in case Threads consumes more processor time, case of context of context switching, Operating system spend more time in managing switching, | 443 ——— ————————Os umn and switching between the th COMPARISON BETWEEN MULTITHREA- DING AND MULTITASKING : DING AND MULTITASKING : Q.2. Define thread. S-12 2M) Q1. What is difference between multiprocessing] | |Q3- Define thread with example. W-12 (4M) and multithreading? 5-09 2m)| | [QA Define thread. Why itis used? 1-13 (4M) QL. WI 1-09, 13,14, W-09,11 (2M) © Each subpart of the program is called thread. Each thread (subpart) have its own path Sr. Multithreading Multiprocessing No. (D | Itisa programming | Teis an operating concept in which a | system concept in program or a process | which multiple is divided into two or | process are performed more subprograms or_| simultaneously threads that are executed at the same time in parallel. @) | ltsupports execution | Tt supports execution of multiple parts of a_ | of multiple program single program simultaneously. simultaneously. @ | The processor has to | The processor has to switch between switch between different parts or different program or threads of a program _| processes. (@ | Weis highly efficient. | Ttis less efficient in comparison to multithreading. (8) | A thread is the ‘A program or process is the smallest unit in a multitasking environment. smallest unit in multithreading, execution, Program Subprogram }-* Program (thread) 1-*Lines of program ep Lines of subprogram Program Threads Fig.4.44 (a) Representation of program and threads © The java run-time system depends on thread. The benefit of java’s multithreading is that, one thread can pause without stopping other part of our program. ‘The time of the CPU can be utilised by the other thread when one thread reads data from network or waits for something. A thread can be in various stages of execution A thread can be runt ‘A thread can be ready to run as soon as it gets CPU time.by ay Ww W wo Tet Hook Serder + he sanopendod \ running thie \ thvead can be blocked \ cuapened thread can be wea MW any the thread can ba te Hoole application progeny that bs aamining on a {he proces for each proyeramn system Hocated for the work dane toe consist Iithvead tine A thioad is 0 progeam's path of execution The above two are the simple definition which cil to define a thread, mre Ath cial comprises a thread 1D, a program Jer set anda 1 arey ction and. files Aion, dat revources like oper A thread shares the cod yite reads belongsing, to 1 ‘other operati with other ali [nn] _Thvead ; 3 4 3 5 Fig.44.4(b) Singlo-thread process cot] [cw | [ton conto] | [roasore] | [rasta wick || [ce || Fee 3 3 ; i 3 Flg.AAA(c) Multithreaded process Example: Write a program to create (wo threads 10 one thread will print 1 to 10 number whereas second thread will print 11 (020 number. 15-10(500), S-L1(4M) | JAVA PAOGEMIINE (OF 88H niends Thread whine int no, julie New Shveadt String, int no) t supertny, this.noeno, stant J, i public void run () { for (int i= 0; 1 105 194) { stem.out printin(getNarnel ) + +(no 0+ iy try Thread . sleep (500) ; } catch (Exception ¢) { System.out.printin (“e"), t public class MyThread { public static void main(String [ ] args) 1 NewThread newThread] = new NewThres! (Thread!:”, |) ew NewThread "1 NewThread newThread2 ‘Output: Thread 1:1 ‘Thread 2:11 ‘Thread 1:2 ‘Thread 2 : 12 ‘Thread 1:3 ‘Thread 2:13 ‘Thread 1:4| Thread 2:19 Thread 1: 10 /ENTALS placed in three places, Thread class. @) Certain part of java.lang.Object-class. (3) Certain functionality of java language and runtime environment. + In java every thread correspond to instance of Thread class. These objects can be in various state. + At any moment at most one object is executing, while other may be waiting for resources or waiting for chance to execute or sleeping or dead. Java's multithreading system is based upon Thread class, its method and its compare on interface Runnable. + To create a new thread, the program will either extend Thread class or implements Runnable interface. * The Thread class define several methods. The ‘most common methods are : (getName ) : The general syntax is “final publicString getName ) This method is used to obtain a thread name, getPriority( ) : The general syntax is Ainal public int getPriority( ) This method is used to obtain a priority of the thread, The default priority of thread is 5. Minimum Priority is 1 and maximum priority is 10. JAVA PROGRAMMING (DIP. V SEM. CO,CMIF) Set Name() : The general syntax is final public void setName (string) This method is used to assign certain name to thread. Gv) Set Priority( ) : The general syntax is Final public void setPriority (int) This method is used to assign new priority of the thread. The default priority of thread is 5, Minimum priority is 1 and maximum priority is 10. (W)_isAlive ( ) : The general syntax is final public boolean isAlive( ) This method is used to check whether the thread is alive or dead. It returns true if thread is alive else false, Join () : The general syntax is : final public boolean join () ‘This method wait until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Stop( ) : The general syntax is : final void stop ‘This method is used to kill the thread. It stops the thread. (viii) Steep( ) : The general syntax is : < fiwal void sleep (long millisecond) throws Interrupted Exception. ‘This method is used to forces a thread to go for a sleep for specified amount of time. After Waking, the thread will again join the Queue. (ix) Fun () : The general syntax is : ‘void num( ) ‘This method is defined in the thread class. It acts as entry point for thread. Every thread start execution from run method. (x) Start () : The general syntax is void start ( ) This method is defined on thread class. It is used to start a thread. This method submit the object of thread type to scheduler which schedule it for execution and then calls run( ).DJ- Text Book Series ae pend ( ): The general syntax is final public void suspend ( ) This method is defined in the thread class. It is wy used fo suspend a thread for indefinite time. A suspended thread will be called for execution only when it is resumed, (A) Resume ( ): The general syntax is final public void suspend ( ) This method is defined in thread class. It is used ‘0 call a suspended thread which is suspended by suspend method. ‘The table below shows thread class methods : Method Deseription getName (String) | Obtain a threads name setPriority (wait) | Obtain threads priority is Alive) Determine if thread is stil Tuning or dead, Join) Wait for a thread to terminate, run() Entry point for the thread slecp() suspend a thread by calling start () Start a thread by call method, Set new name of thread. ity of thread. setName(string) [ SetPriority Gint) Sets new pi 4.4.6 THE MAIN THREAD : a6 THE MAIN THREAD : * When a java program starts up, one thread begins ig immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins. The main thread is important for two reasons : It is the thread from which other “child” threads run will be spawned, (ii) Often, must be the last thread to finish execution because it performs various shutdown actions. * Although the main thread is created automatically when our program is started, it can be controlled through a thread object. To do so, we must obtain Spawned - tera, arate 4 RAMMING (DIP. SEM. cr, JAVA PROG! it by calling, the metho fa reference 10 it by bese Tivend( ) « which is a public static form is shown here thread, Its general form is a static thread current Threa This method returns a reference to the thy, which it is called, Once we have a refer, the main thread, we can control it just jpg he other thread. Example : ; , U/Controlling the main Thread. class Current threadDemo i A public static void main (String argsf}) { Thread t = Thread.current Thread ( ); System , out.printIn(“current Thread : "+ 1). W change the name of the thread t. setName (“My Thread”) ; System.out.printIn (“After name change :" +) try { for (intn=5;n>0;n—~) { System.out printin(n) ; Thread.sleep (1000) ; } catch (InterruptedExceptione) { System.out.printIn (“main thread interrupted”) ; } } } In this program, a Teference to the current thread (the main thread, in this case) is obtained 4 calling current Thread ( ), and this reference 6 Stored in the local variable t. Next, the progres displays information about the Thread. ‘The Program then calls setName (to chanse internal name of the thread. Information 3%! thread is then redisplaye areat Book Series Next loop counts down from five pausin al nd between each The vans one sesomplished by the sleep ( ) method, “8 se argument t0 sleep () specif in milliseconds. line, is the delay period qhe sleep () method in thread might throw interuptException. This would happen if — ciher thread wanted to interrupt this sleeping one, this example just prints a message if it gets interrupted. Here is the output generated by ‘he gram ° (Current thread : Thread [main ; 5, main] ‘Afiername change : Thread [My Thread, 5, main] * As the preceding program shows, we can JAVA PROGRAMMING (DIP.V SEM. CO.CM.IF) milliseconds and nanoseconds static void sleep (long milliseconds, int nanoseconds) throws InterruptedException. * This second form is useful only in environments that allow timing periods as short as nanoseconds. set the name of a thread by using setName( ). * We can obtain the name of a thread by calling not shown in the get Name( ) (but note that thi program). These methods are members of the thread class and are declared like this : final void setName (String threadName) final String getName( ) Here, threadName specifies the name of the thread. 45CREATING A THREAD produced when ‘t’ is used as an argument to printin ( ). This displays, in order, the Stree Qu. Explai fferent ways to create thread. W-11 (2M) name of thread, its priority, and the name of its group. By default, the name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs. A thread group is a data structure that controls the state of a collection of threads as a whole. After the name of the thread is changed, ‘t’ is again output. This time, the new name of the th displayed, The sleep ( ) it is called to suspend execution for period of milliseconds. Its general form is shown here: static void sleep (long InterruptedException. The number of milliseconds specified in milliseconds. This method may throw’ an InterruptedException. ‘The sleep ( ) method has a second fo Which allows us to specify the perio read is method causes the thread from which wr the specified milliseconds) throws to suspend is rm, shown next, din terms of ‘© Threads are implemented in the form of objects that contain a method called run ( ). + Creation of thread is basically performed by following methods : Thread Thread Runnable (cass) (interface) Overide 1 run) methoa Fig. 4 Creation of thread «The run () method is the heart and soul of any thread. it makes up the entire body of a thread and is the only method in which the thread’s behaviour can bbe implemented. © Atypical run () would appear as follows :6 (01. Vem . “java PROGRAMMING (01D Coen DJ Text Book Series aaa) od on the instang ublic void run () {iv)_Invoke the start () method on so p class make the thread eligible for sunning { Example = 7 class MyThread Extends Thread { . " String s= null =~ (statements for implementin, < ae " ° My thread (String S!) } { =sl; + The run ( ) method should be invoked by an ae object of the concemed thread. This can be sans achieved by creating the thread and initiating it Deere) With the help of another thread called start (). publie voi | new thread can be created in two ways : ' : ‘System.out.printIn (S) ; | (Y By creating a thread class: } a * A java program creates a thread by instantiating , | thread object and manipulate it. ) public class RunThread | Creating and launching a thread is something { called spawning a thread. public static void main (String args []) class : java.lang. Thread { This class provides a infrastructure for MyThread ml = new My Thread (“Thread ‘multithreaded progeams in java, started ....”) * Constructors used for creating a thread are : } Thread () d Thread (Runnable object) Output: Thread (String name) C:\j 2506 \ thread > java c RunThread . ja :\j 2 se6\ thread > java RunThread. Thread started Thread (Runnable object, String name) Thread (Thread Group group, Runnable object) Thread ( Thread Group group, StringName) Following table shows the methods to create a Thread (Thread Group group, Runnable object, thread class : String name) Fr Methods Description _| + For creating a thread we have to follow the | [eurrentThread () Rena mises te following steps currently executing (i) Extend the java . lang . Thread class. _. Thread. (ii) Override the run (.) method in the subclass from me N ae Returns thread priority the thread class to define the code executed by the interrupe(} Pbtains a thread name al interrupts the current (iii) Create an instance of this subclass. This subclass | | is Daemon () a eee may call a thread class constructor by subclass stein teaetete constructor. false, __J Invoke - 3167, AE oext Book Series ait) 's Aliveretum wus thread has been started and has not yet dead else false, gia done miliscconds) Wait for a thread to terminate, Di Entry point of thread. It implement Runnable interface Sets prority of thread . Suspends thread for a Period of time,
0;i--) ( System.out.printIn (“Child Thread: ” +i); Thread . sleep(500) ; } } catch (InterruptedException e) i System.out.printin(“Child interrupted. ) System out printin( “Exiting child thread”) ; ) ) class ThreadDemoDJ Text Book Series ‘ args 11) { Dublie static void main (String newThread () ; Hereate a new thread ty { for (int Ssi>0;i--+¢ System.out.printIn(“Main Thread : “+ i); Thread .sleep(1000) ; } } catch (InterruptedException e) { System.out, PrintIn(“Main thread interrupted.”) ; } System.out.printin¢*Main thread exiting.”); } } Inside New Thread's constructor, a new thread object is created by the following statement : t= newThread (this, “DemoThread”) Passing this as the first argument indicates that we want the new thread to call the run () method on this object, Next, start () is called, which starts the thread of execution beginning at the run () method. This causes the child thread’s for loop to begin. After calling start ( ) , NewThread’s constructor returns to main( ). When the main thread Tesumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish The output produced by this program is as follows. (our output may vary based on processor speed and task load) ‘Output: Child thread : Thread [Demo thread , 5, main ] Main Thread : 5 Child Thread : 5 Child Thread : 4 Main Thread : 4 Child Thread : 3 Child Thread : 2 420 JAVA PROGRAMING (IP. 514 o Child Thread : 1 Exiting child thread Main Thread : 2 1 Main Thr Main Thread © Tn a multithreaded program, offen the mai must be the last thread to finish running. 4, Py for some older JVMs, if the main thread f, before a child thread has completed, then run-time system may “hang”. The preceding program ensures that the ma. thread finishes last, because the main tj sleeps for 1,000 milliseconds between itera, but the child thread sleeps. for only sy milliseconds, This causes the child thea, terminate earlier than the main thread, Mish he ayy D CLASS XTENDING THE THE The second way to create a thread is to create» new class that extends Thread, and then to cri an instance of that class. The extending cles must override the run () method, which isthe entry point for the new thread. It must also call start () to begin execution of the new thread. Here is the preceding program rewritten to extend Thread : W Create a second thread by extending thread Class New Thread extends Thread { ‘New thread () { 4 Create a new, second thread super(“Demo thread”) ; System.out printin (“Child thread :" + this); start ();/start the thread } 1 This is the entry point for the second thread. public void run () ty for (inti= 5 51>0;4-— { System.out printin (“Child Thread :”+ i); Thread . sleep(500) ;sh Interrupted Exception e) system out pritIn(*Child intereupted» sem out.printIn(“ENiting child thread") jass Extend Thread { ae puble static void main (String args () { new NewThread (); //create a new thread wy { for (int i { system out.printIn(“Main Thread :" +i); Thread sleep(1000) ; } } catch (Interrupted Exception ¢) { system.out.printIn(“Main thread interrupted.”) ; } system.out.printIn(“Main thread exiting.”) } } This program generates thi preceding version. As we can see, is created by _instantiating New Thread, which is derived from thread. Notice the call to super ( ) inside New Thread This invokes the following form of the Thread 1e same output as the the child thread an object of constructor : public Thread (Stringthread Name) Here, thread Name specifies th of the thread, e name Preceding examples, this i 1g sleep () within main ( » delay to ensure that all child 1 Prior to the main thread. r7_sava procrammin (O1P.v SEM. CO.CMIF) * However, this is hardly a satisfactory solution, and it also raises a larger question : How ean one thread know when another thread has ended? Fortunately, Thread provides a means by which We can answer this question. Two ways exist 10 determine whether a thread has finished. ‘© First, we ean call isAlive () on the thread. This method is defined by Thread, and its general form is shown here final boolean isAlive () ‘© The isAlive (.) method returns true if the thread ‘upon which it is called is still running. It returns false otherwise. © While isAlive () is occasionally useful, the method that we will more commonly use to wait for a thread to finish is called join (), shown here: final void join () throws InterruptedException. ‘© This method waits until the thread on which itis called terminates, Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join () allow us to specify a maximum amount of time that we want to wait for the specified thread to terminate. Here is an improved version of the preceding example that uses join ( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive () method. Example Using join () to wait for threads to finish. class New Thread implements runnable { string name :// name of thread ‘Thread t NewThread (String threadname) { name = threadname ; t= new Thread (this, name) ; system.out.printin("New thread :"+) 5 tstart( ); “Start the thread } W This is th public void run () 1e entry point for thread.DJ- Text Book Series “0 —— 7 = Sample output from this program js \ vary based on proce try { (our output may ae p for (inti=5;i>0;i--y 4 Speed and task load.) System.out.printin (name +: + i); Output: Thread sleep(1000) ; } } catch (InterruptedExcept System.out.printIn(name + } System out printin(name + exiting.”) ; , 3 class DemoJoin { Public static void main (String args []) { NewThread ob] = new NewThread (“One” NewThread ob2 = new NewThread (“Two” NewThread ob3 = new NewThread (“Three”) ; System.out.printIn(“"Thread One is alive :"-+ obl.t. System.out.printin(“Thread Two is al ob2.t. isAlive ()); ‘System.out.printIn(*“Thread Three is alive : "+ 0b 3.t. isAlive ( )) // wait for threads to finish wry { ‘System.out.printin(“Waiting for threads to finish.”); obl.tjoin(); ob2.tjoin(); ob3.tjoin (); } catch (InterruptedException e) { ‘System.out.printIn(“Main thread interrupted.” ; } System.out.printIn(“Thread One is alive :” + obl.t. isAlive ()) ; System.out.printIn(““Thread Two is alive :”-+ ob2.t. isAlive ()); System.out printIn(“Thread Three is alive :” + 0b3.t. isAlive ()) ‘System.out.printin(“Main thread exiting.”) ; } } New thread . Thread [One, 5, main} New thread . Thread (Two, 5, main} New thread . Thread (Three, 5, main] Thread One is alive : true Thread Two is alive : true Thread Three is Waiting for threads to finish, true One : 5 Two:5 Three: 5 One: 4 Two:4 Three: 4 One : 3 Two :3 Three :3 One : 2 Two :2 Three : 2 Two exiting, Three exiting, One exiting, Thread One is alive : false Thread Two is alive : false Thread Three is aliv Main thread exiting, : false ———_ AS we can see, afer the calls to join (), tu threads have stopped executing py 2 er CLE OF TREAD : — ‘san peseribe the complete life cycle of 7 Vy ‘Yele of threads, 1W-08,10,14 (4M), W116, 8-14 (any 12 Fxplain Tife cycle of thread a je! disgram. along with] 5-09, W-09,13 (4M), S-11, W-12 (8M MSBTE-SOP (3M) 3. With suitable diagram explain the lite ad of thread. ‘8-13 (8M) During the life time of a thread, there are many states it can enter. They include. (1) Newborn state. @) Runnable state. (3) Running (4) Blocked state. (5) Dead state. A thread is always in one of these five states. It ‘can move from one state to another via a variety Fig.4.6.(a). Nun- Rennable der miinote do: of ways shown New thread Newborn [= CD Active thread Conn) Killed thread suspend resume sleep wait notify ‘sop Idle thread (Not Runnable) ofa thread Fig. 46 (a) State transition diagra™ () Newborn state : * When we create a thread objec! to be in newborn state. 4, the thread is born at Relinguish - ore er, wert. 1p. V SEM. CO.C! LAVA PROGRAMMING (0! led for running, At of the following The thread is not yet schedu this state, we can do only one things with it (i Schedule it for running using start ( ) method. (ii) Kill it using stop () method. If scheduled, it moves to the runnable state. Fig.4.6(b). If we attempt to use any other method at this stage, an exception will be thrown Fig. 4.6 (b) Scheduling a newborn thread Runnable state + The runnable state means that the thread is ready for execution and is waiting for the availablity of the processor. ‘That is, the thread has joined the queue of thread that are waiting for execution. If all threads have equal priority; then they are given slots for execution in round robin fashion, i.e. first come, first serve manner. The thread that relinquishes control joins the {queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing. — However, if-we want a thread to relinquish control to another thread to equal priority before its turn comes, we can do so by using the yield () method. eld © Running Runnable threads thread {) Relinquishing control using yield{) method. Fig.
You might also like
Exception Handling
PDF
No ratings yet
Exception Handling
16 pages
Unit-4 Java
PDF
No ratings yet
Unit-4 Java
42 pages
JP Unit 4
PDF
No ratings yet
JP Unit 4
83 pages
Managing Errors and Exceptions
PDF
No ratings yet
Managing Errors and Exceptions
38 pages
Unit 4
PDF
No ratings yet
Unit 4
83 pages
Exception Handling in Java
PDF
No ratings yet
Exception Handling in Java
19 pages
JAVA Exception handling most important question
PDF
No ratings yet
JAVA Exception handling most important question
19 pages
Unit 4
PDF
No ratings yet
Unit 4
83 pages
unit 4
PDF
No ratings yet
unit 4
62 pages
JPR Unit 4
PDF
No ratings yet
JPR Unit 4
24 pages
Java-UNIT 3 PDF
PDF
No ratings yet
Java-UNIT 3 PDF
37 pages
Lecture 12 Exception Handling With Assertion
PDF
No ratings yet
Lecture 12 Exception Handling With Assertion
73 pages
Exception Handling I
PDF
No ratings yet
Exception Handling I
21 pages
Chapter-1 Exception Handling in Javan - Rvu
PDF
No ratings yet
Chapter-1 Exception Handling in Javan - Rvu
101 pages
Lec 23
PDF
No ratings yet
Lec 23
20 pages
Exception Handling by Ayush
PDF
No ratings yet
Exception Handling by Ayush
7 pages
Managing Errors and Exception
PDF
100% (2)
Managing Errors and Exception
12 pages
Java
PDF
No ratings yet
Java
4 pages
JAVA Unit 4
PDF
No ratings yet
JAVA Unit 4
100 pages
Java Unit-5 Exceptions Handling
PDF
No ratings yet
Java Unit-5 Exceptions Handling
41 pages
Unit-2 Exception Handling and IO Streams
PDF
No ratings yet
Unit-2 Exception Handling and IO Streams
40 pages
Java Unit-2 One Shot Marathon Notes
PDF
No ratings yet
Java Unit-2 One Shot Marathon Notes
55 pages
Exception Handling
PDF
No ratings yet
Exception Handling
16 pages
220245-MSBTE-22412-Java (Unit 4)
PDF
No ratings yet
220245-MSBTE-22412-Java (Unit 4)
19 pages
OOP Unit 51
PDF
No ratings yet
OOP Unit 51
126 pages
Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
PDF
No ratings yet
Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
5 pages
Chapter 09 - Exception Handling
PDF
No ratings yet
Chapter 09 - Exception Handling
26 pages
FP301 Chapter3 Exception - Handling
PDF
No ratings yet
FP301 Chapter3 Exception - Handling
23 pages
Exception Handling
PDF
No ratings yet
Exception Handling
15 pages
OOPLecture9Exception Handling
PDF
No ratings yet
OOPLecture9Exception Handling
23 pages
MZ Chapter - 4 and 5 - Exception Handling and Packages Oop
PDF
No ratings yet
MZ Chapter - 4 and 5 - Exception Handling and Packages Oop
43 pages
Chapter9 ExceptionHandling
PDF
No ratings yet
Chapter9 ExceptionHandling
13 pages
Java Unit-3.1.final
PDF
No ratings yet
Java Unit-3.1.final
66 pages
Exception Handling in Java
PDF
No ratings yet
Exception Handling in Java
7 pages
Unit 4
PDF
No ratings yet
Unit 4
38 pages
Java Unit4
PDF
No ratings yet
Java Unit4
19 pages
4.exception Handling and Multithreading
PDF
No ratings yet
4.exception Handling and Multithreading
91 pages
Java Unit-Iii
PDF
No ratings yet
Java Unit-Iii
43 pages
unit 4 java
PDF
No ratings yet
unit 4 java
46 pages
Exception Handling, Basics of Multi-Threaded Programs
PDF
No ratings yet
Exception Handling, Basics of Multi-Threaded Programs
94 pages
14.exception Handling - Try Catch
PDF
No ratings yet
14.exception Handling - Try Catch
37 pages
Unit3 OOPS
PDF
No ratings yet
Unit3 OOPS
78 pages
Exception Handling
PDF
No ratings yet
Exception Handling
21 pages
Exceptions: An OO Way For Handling Errors
PDF
No ratings yet
Exceptions: An OO Way For Handling Errors
27 pages
Object oriented programming Chapter 05
PDF
No ratings yet
Object oriented programming Chapter 05
15 pages
UNIT-III
PDF
No ratings yet
UNIT-III
28 pages
4 Exception Handling
PDF
No ratings yet
4 Exception Handling
34 pages
java Chapter 6 Exceptions
PDF
No ratings yet
java Chapter 6 Exceptions
29 pages
Exception Handling
PDF
No ratings yet
Exception Handling
35 pages
Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
PDF
No ratings yet
Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
43 pages
Exceptions Exceptions: Lecture 09
PDF
No ratings yet
Exceptions Exceptions: Lecture 09
20 pages
Chapter 4 Exceptions Short Lecture
PDF
No ratings yet
Chapter 4 Exceptions Short Lecture
39 pages
Exception Handling
PDF
No ratings yet
Exception Handling
12 pages
Exception Handling-Converted New
PDF
No ratings yet
Exception Handling-Converted New
5 pages
What Is Exception: Throwable
PDF
No ratings yet
What Is Exception: Throwable
31 pages
Java Unit3
PDF
No ratings yet
Java Unit3
119 pages
Unit 3 - Exception Handling
PDF
No ratings yet
Unit 3 - Exception Handling
29 pages
Chapter 6 Exception Handling
PDF
No ratings yet
Chapter 6 Exception Handling
44 pages
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
Exception Handling
PDF
Exception Handling
Unit-4 Java
PDF
Unit-4 Java
JP Unit 4
PDF
JP Unit 4
Managing Errors and Exceptions
PDF
Managing Errors and Exceptions
Unit 4
PDF
Unit 4
Exception Handling in Java
PDF
Exception Handling in Java
JAVA Exception handling most important question
PDF
JAVA Exception handling most important question
Unit 4
PDF
Unit 4
unit 4
PDF
unit 4
JPR Unit 4
PDF
JPR Unit 4
Java-UNIT 3 PDF
PDF
Java-UNIT 3 PDF
Lecture 12 Exception Handling With Assertion
PDF
Lecture 12 Exception Handling With Assertion
Exception Handling I
PDF
Exception Handling I
Chapter-1 Exception Handling in Javan - Rvu
PDF
Chapter-1 Exception Handling in Javan - Rvu
Lec 23
PDF
Lec 23
Exception Handling by Ayush
PDF
Exception Handling by Ayush
Managing Errors and Exception
PDF
Managing Errors and Exception
Java
PDF
Java
JAVA Unit 4
PDF
JAVA Unit 4
Java Unit-5 Exceptions Handling
PDF
Java Unit-5 Exceptions Handling
Unit-2 Exception Handling and IO Streams
PDF
Unit-2 Exception Handling and IO Streams
Java Unit-2 One Shot Marathon Notes
PDF
Java Unit-2 One Shot Marathon Notes
Exception Handling
PDF
Exception Handling
220245-MSBTE-22412-Java (Unit 4)
PDF
220245-MSBTE-22412-Java (Unit 4)
OOP Unit 51
PDF
OOP Unit 51
Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
PDF
Exceptions: An OO Way For Handling Errors I Ntroduction: Without Error Handling - Example 1
Chapter 09 - Exception Handling
PDF
Chapter 09 - Exception Handling
FP301 Chapter3 Exception - Handling
PDF
FP301 Chapter3 Exception - Handling
Exception Handling
PDF
Exception Handling
OOPLecture9Exception Handling
PDF
OOPLecture9Exception Handling
MZ Chapter - 4 and 5 - Exception Handling and Packages Oop
PDF
MZ Chapter - 4 and 5 - Exception Handling and Packages Oop
Chapter9 ExceptionHandling
PDF
Chapter9 ExceptionHandling
Java Unit-3.1.final
PDF
Java Unit-3.1.final
Exception Handling in Java
PDF
Exception Handling in Java
Unit 4
PDF
Unit 4
Java Unit4
PDF
Java Unit4
4.exception Handling and Multithreading
PDF
4.exception Handling and Multithreading
Java Unit-Iii
PDF
Java Unit-Iii
unit 4 java
PDF
unit 4 java
Exception Handling, Basics of Multi-Threaded Programs
PDF
Exception Handling, Basics of Multi-Threaded Programs
14.exception Handling - Try Catch
PDF
14.exception Handling - Try Catch
Unit3 OOPS
PDF
Unit3 OOPS
Exception Handling
PDF
Exception Handling
Exceptions: An OO Way For Handling Errors
PDF
Exceptions: An OO Way For Handling Errors
Object oriented programming Chapter 05
PDF
Object oriented programming Chapter 05
UNIT-III
PDF
UNIT-III
4 Exception Handling
PDF
4 Exception Handling
java Chapter 6 Exceptions
PDF
java Chapter 6 Exceptions
Exception Handling
PDF
Exception Handling
Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
PDF
Cs8392 Object Oriented Programming: Unit Iii Exception Handling and I/O
Exceptions Exceptions: Lecture 09
PDF
Exceptions Exceptions: Lecture 09
Chapter 4 Exceptions Short Lecture
PDF
Chapter 4 Exceptions Short Lecture
Exception Handling
PDF
Exception Handling
Exception Handling-Converted New
PDF
Exception Handling-Converted New
What Is Exception: Throwable
PDF
What Is Exception: Throwable
Java Unit3
PDF
Java Unit3
Unit 3 - Exception Handling
PDF
Unit 3 - Exception Handling
Chapter 6 Exception Handling
PDF
Chapter 6 Exception Handling