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

Threads&exceptions UNI T 3

java bsc iii year
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
0% found this document useful (0 votes)
127 views

Threads&exceptions UNI T 3

java bsc iii year
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
You are on page 1/ 15
CoS we Wy ; UNITIL Multi Threaded Programming Vai ty of executing several programs simultaneously is known as Multitasking,in system’s terminology it is known as MultiThreading. MultiThreading is a conceptual programming where a program is divided into two or more subprograms,which can be implemented simultaneouslyin parallel.The processor is doing only one thing at a time. However the processor switches between the processes so fast that is appears (us that all of them are being done simultaneously.java programs that we have seen and discussed so far contain only a single sequential flow of control. A thread is similar to program that has a single flow of control.It has a beginning body,and an end and executes commands sequentially. In fact all main programs in.our earlier examples can be called single threaded programs.A unique property of java is it’s support for MultiThreading. That is java enables to use multiple flows of control in developing programs Each flow of control is aseperate tiny program (or module)known asa thread.a program that contains multiple flows of control is known as multithreaded program.The ability of a language to support multithreads is reffered to as concurrency,Since threads are subprograms of a main application program and share the ‘same memory space, they are known as lightweight processes or lightweight threads. Main thread curttches Thread C Thread A wou Thread B a Sa a Threads ‘Anew thread can be created in two ways. By creating a thread class 2)By converting a class to a thread Extending the Thread class By extending java,lang. read we can make our class runnable as a thread )Declare the class as extending the thread class 2)implement the run() method that is responsible for executing the sequence of code that the thread will execute, 43)Create a thread object and call start() method to initiate the thread execution. & Scanned with OKEN Scanner ‘Syntax: h class MyThread extends Thread { -dithread code Starting new thread: To actually create and an instance of our thread class,we must write the following, EX: class A extends Thread { public void run() { for(int i=1;i<*5;i++) { System.out.printIn(‘\t from thread A i= } System.out.printIn(“exit from A”)” } } class B extends Thread public void run() { System.out.printIn(““\t from thread B jPts } System.out.printIn(“‘exit from B”)” } class ThreadTest { public static void main(String args[]) { eer en er & Scanned with OKEN Scanner 1 YI Bu ruovbbbbEbE eed ddddcoceceroe | es LCUEuUuYvYvMeU VV vy A tl=new AQ; i \ B (2=new BO; U.startQ; 2.startQ; } } ‘Stopping a thread’ Whenever we want to stop a thread from running further, we may do so by calling i's stop() method. | t1.stopQ; this statement causes the thread 6 move to the dead state. Blocking a thread: ‘thread can also be temporarily suspended or blocked from entering into the runnable state by using either of the following thread methods. sleep(time); _// blocked for a specified time suspend(); I blocked until further orders wait; 11. blocked until certain condition occurs. ced state. The thread will return to “These methods cause the thread to go into the block runnable state when the specified time is elapsed in the case of sleep), the resume() tmathod invoked in the case of suspend( and natify() is called in the ease of wait method. eerie _— & Scanned with OKEN Scanner Sis Lifecycle of a Thread During the life time of a thread there are many states it can enter, Newborn running runnable a ee blocked NewBorn state: when we create a thread object,the thread is born and is said to be in newborn state.At this state we can do ony one of the following things. 1)schedule it for running using start() method2)kill it using stop() method. new born states Runnable Dead state state Scanned with OKEN Scanner Runnable State: The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority,then they are given timeslots for execution in roundrobin fashion.i.e first serve manner. The process of assigning time to threads is known as timeslicing, However if we want a thread to control another thread of equal priority before its tum comes,we can do so by using yield() method. yidlo) Qecwol> © Qo 1 eda it’s ) Running state: running means that the processor has given its time to the thread for it execution. ae ) Tit has been suspended using suspend()method.thread re enters the runnable state PY using resume() method. , © Quoi Raweble nur Rloe ) ) Apel j i i i ing the method ‘a specified time period using t ) areca tated gee ae tomes 28 * sleep(time),w +) this time is elapsed. Qawneble - ) Bure? poy), Blocked Wat) ol until some event oceurs.This is done ws g the wait() metho it until vent s.This is done using t 1d to wait until some event 3)It has been tol Frread ean be scheduled to run again using the notify() method, athre & Scanned with OKEN Scanner Blocked stat A thread is said to be blocked w hen it is prevented from entering into runnable state and running state. This happens when the thread is suspended,sleeping or waiting.A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again. Dead state: 7 A running thread ends it’s life when it has completed executing it’s run()method.It is a natural death, We can kill it by sending stop message to it.A thread can be killed as soon as it is born or while it is running or even when it is in not runnable(blocked)condition. Example program using thread methods: class A éxtends Thread public void run() { for(int i=;i<5;: 1i==1)yieldQ; System.out.printIn(“from thread A } System.out.println(“exit from A”); 3 class B extends Thread { public void run() { for(int j=1;j<=5;j++) System.out.println(“‘from thread B:J="+J); IfG==3) System.out.printIn(“exit from B"); } } class C extends Thread { public void run() { for(int k=1;k<=5;k++) System.out.println(“from thread C:k="*+k); If{k==1) Try { Sleep(1000); } Scanned with OKEN Scanner catch(Exception e) } } | System.out.printin(“exit from C”); } Class ‘ThreadMethods ae static void main(String args{]) Atl=new AQ; B t2=new BO; ~ Ct3=new CQ; System.out.printin(“start thread A”); tL.start0; : System.out.printIn(“‘start thread B”); t2.start(); System.out.printin(“start thread C” 1B.start(); System ou printing of main thread”); } Thread Exceptifons Note that the call to sleep () method is enclosed in a try block and followed by catch bllock.This is necessary because the sleep) method throws an exception, which should be caught.[f we fait to catch the exception program will not compile. Java run System will throw IllegalThreadStateException whenever we attempt to invoke a method that a thread can’t handle in the given state. for ex: a Sleeping thread can’t deal with the resume()method. whenever we call a thread method that is likely to throw an exception,we have to supply an appropriate exception handler to catch it. catch(ThreadDeath e) { //killed thread } catch(InteruptedException €) { // can’t handle it in the current state catch(lllegalArgumentException e) { ‘illegal method argument Scanned with OKEN Scanner catch(Exception e) { Jany other Thread priority: In java each thtread is assigned a priority,which affects the order in which it is scheduled for running.the threads of same priority are given equal treatmentby the java scheduler and therefore they share the processor on a first come first serve basis. Tava permits us to set the priority of a thread using the setPriority()method. SY: Threadname.setPriority(integernumber); MIN_PRIORITY=1 NORM _PRIORITY: MAX_PRIORITY=10 ‘The integer number mafjassume one of the these constnts or any other value between 1% and 10.the default settifig is NORM_PRIORITY. By assigning priorities to threads,we can ensure that they are given the attention they yses the deserve,whenever multiple threads are ready for execution the java system choo: highest priority thread and executes it.for a thread a lower priority to gain control one of the following things should happen. 1) Itstops running at the end of run() 2) Itis made to sleep using sleep() 3) It is told to wait using wait() However if another thread of a higher priority comes along the currently will be pre-empted by the invoking thread thus forcing the current thread to move to the running thread runnable state. class A extends Thread { public void run() { System.out.printin(“thread A started”); for(int i=1si<=5;i++) { System.out.printIn( “from thread A: 3 System.out.printIn(“exit from A”); } } class B extends Thread { public vuid 1un() { System.out.printin( “thread B started”); Sit) & Scanned with OKEN Scanner ~ ves yu System.out.printin(“from thread B. System.out.printIn(“exit from B”); } class ThreadPriority { public static void main(String args{]) Atl=new AQ; B 2=new BO; tL setPriority(Thread. MAX_PRIORITY); 12.serPriority(Thread.MIN_PRIORITY); System.out.printin(‘START THREAD A”); tL.startQ; ‘System.out printin(“START THREAD B”); t2.startQ; System.out.println(“end of main threa 3 3 & Scanned with OKEN Scanner (a) Implementing Runnable Interface ‘The simple and casiest way for creatis : fay for creating a thread is t i _ i read is to create a class which implements the ‘Runnable’ ime Ws poss ae Construct a thread irrespective of object which implements “Renna This nerte hides aU le. The implementation of ‘Runnable’, interface is done by implementing a single method called run( ), which contains the creation code similar to m ad. The run( ) n simitla a dnoke other methods, other classes and also to declare variables cee ae cee syntax public void run() ‘After creating a class which implements ‘Runnable’, an obj, . , the class. One of the important constructors defined by “Thread” an oo ‘Thread(Runnable thObj, String tName) stantiated from within Here, thObj — Instance of a class which implements the runnable interface. tName —Name of the new thread. Once the new thread is created, execution of it can be initiated using its start() method. Example import java.io.*; class ThreadDemo implements Runnable { public void run() { System.out.printin(“The thread is created using runnable interface”); } public static void main(String ares{ }) { ThreadDemo dl=new ThreadDemo( ); ‘Thread thi =new Thread(dl); thi start( ); + } @ Scanned with OKEN Scanner naging errors and Exeep a.com e mis i ae aniline ke mistakes while developing as well as typing « program, A ght lead {0 un error causing the program to pt * eal ni am to produce unexpected results, Errors are wrong that ean make a program go wrong. : Ba ' Types of Err 1) Compilation errors 2) Runtime errors UD eat be detected and displayed by the java compil sr and therefore these ee oe ope ome ne ar Whenever the compiler displays an enor ie vill eee ig therefore necessary that we fix all the errors before we ean ee pile and run the program, Most of the compile time errors are typing mistakes e may have to chek the eode by ‘word or even character hy ¢ non problems are 1) missing semicolons 2) missing or mismatch of () bracke 3) misspelling of identifiers and keywords 4). missing double quotes in strings 5) use of undeclared variables 6) bad reference to object 7) use of = in place of = in classes and methods operator etc. other errors we may encounter are related to directory paths.An error such as javac:command not found Java spat we have not set path correctly we must ensue 1h directory where the java executable are stored. at the path includes the Runtime Errors: Sometimes a program may compile successfully ereatin properly. Such program may produce V°Ens results duc to wr are io errors such as stack overflow. Most of common run 1) Dividing an integer by 2er0 2) Accessing an element that is ov! of the bounds of an array 3) Trying to store a value into an arty ‘of an incompatiable class or WyPe notin a valid range or values for method 44) Passing a parameter that is ise a negative size for array 5) Attempting tov {) Connecting invalid string (0.4 number 1p the .clas file but may not run ‘ong logic or may tenninate J errors are: class Error public static void main(String args| }) int a=10,int b=9, 6=5; & Scanned with OKEN Scanner int x=a/(b-c); System. out.printIn(“x="4); int y=al(b+0); System.out println(“‘y="+y); } } XA. ceptions ‘An Exception is a condition that is caused by a runtime error in the program when java interpreter finds ,an error such as dividing an integer by zero,it ereates an exception objects and throws it ie informs us that an error has occuerd and terminates the program. ‘When we want to continue with the execution then we should try to catch the exception object and then display an appropriate message .this task is known as Exceptionhandling. he purpose of this mechanism is to detect and report an exceptional circumstance. The mechanism performs the following tasks 1) Find the problem (hit the exception) 2) Inform that an error has occurred (Throw an Exception) 3) Receive the error information(catch Execption) 4) Take corrective actions(Handle the exception) Itconsists of two segments one to detect errors and to throw exception and the other to catch exception to take appropriate actions. Common Java Exceptions: Cause of Exception I caused by math errors such as division by zero 2, caused by bad array indexes 3.caused when a program tries to store the wrong type data in an array 4.caused by an attempt to access a non Existent file S,caused by general I/O failures. 6.caused when a conversion between Strings and number fails “caused when theres not enough Memory to allocate 2 nev object 8.caused when a program attempts To access anon existent character position ina string 1 ArthmeticException 2.ArraylndexOutOfBoundsException 3.ArrayStoreException 4 File Not Found Exception SJOException 6.Number Format Exception 7,0utOfMemoryException 8.StringIndexOutOfBoundsException & Scanned with OKEN Scanner tax of Exception Ha ing cod The basic concept of Exception handling are throwing an exception and catching it Try block \ \ Baeeptton object | Statement that causes ar i ” sanexception | recs Fie 1 Catch block ‘Statement that handles the exception try { statement; //generates an exception i } catch (Exception type ¢) { stmt; //process the exception ts that could generate exceptions.If any one g statement in the block are skipped and ck. The catch block can ‘The try block can have one oF more statement statement generates an exception ,the remanin; execution jumps to the catch block that is placed next to try blo sice have one or more statements that are necessary 0 process the exception veatch works Tine a method definition The catch stint is passed a single parameter which is reference to the exception object thrown by try block.fthe catch parameter ‘matches with the.type of exception object.then the exception caught and statements in eatch block will be executed. class Error { public static void main (String args{ J) 53 int a=10,int b=5, try { x=al(b-c); JI. Exception here catch(ArthematicExeeption e) & Scanned with OKEN Scanner i i | | { System.out.printin(“Division by zero”); 3 yral(bte); } System.out.printIn(“y="+y); Hratiat catch statements: It is possible to have more than one catch statement in the catch block try { ‘stmty// generates an exception } catch( Exception type |e) { stmt; 3 MIprocess exception type | catch(Exception type n e) { stmt; //process exception type n 3 When an exception in a block is generated the java treats the multiple catch statements like cases in switch statement.The statement whose parameter matches with the exception object will be executed and the remaining statement will skipped. Note that java doesn’t require any processing of the exception at all We can simply have a catch statement with ‘an empty block to avoid program abortion. Ex: catch(Exception e); This stmt will catch exception and then ignores it. class Error { . public static void main (string args[ ]) { int af J=(5,10}; int b- try { Int x=a[2]/b-a[ 1]; Scanned with OKEN Scanner d catch(ArthematicException ¢) { System.out.printIn(“division by zero"); } catch(ArrayIndexOutOfBoundsOfException e) { : System.out.printin(“Array index error"); catch(ArrayStoreException ©) { System.out.printIn(“Wrong data type”); } int y=a[1}/a[0]; System.out.printn(“y="+y); } sine Using finally statements Java supports another statement known as finally statement that can be used to handle sn exception that is not caught of the previous catch statements.finally eck can be bo ito handle any exception generated within a try block.tt may be added immediately after the try block o. after the last block. L 2)try va o catch) faaly { ) ) catch() Sa { ; ) finally ae { } : When a finally bloch i exception is thrown. Wi releasing system resources ‘ute regardless of whether or not generated to exect e rations such as closing @ files or s defined this is ) form certain opel fe can use it to per finally { int yal Vals system. out.printin(” a } nay & Scanned with OKEN Scanner

You might also like