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)
127 views
Threads&exceptions UNI T 3
java bsc iii year
Uploaded by
THIRUMALAXEROX INTERNET
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save threads&exceptions UNI T 3 For Later
Download
Save
Save threads&exceptions UNI T 3 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
127 views
Threads&exceptions UNI T 3
java bsc iii year
Uploaded by
THIRUMALAXEROX INTERNET
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save threads&exceptions UNI T 3 For Later
Carousel Previous
Carousel Next
Save
Save threads&exceptions UNI T 3 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 15
Search
Fullscreen
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 Scanner1 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 ScannerSis 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 ScannerRunnable 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 ScannerBlocked 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 Scannercatch(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 Scannercatch(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 Scannernaging 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 Scannerint 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 Scannertax 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 Scanneri 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 Scannerd 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
Java and Multi Threading
PDF
100% (1)
Java and Multi Threading
44 pages
Multithread Programming
PDF
No ratings yet
Multithread Programming
42 pages
Thread
PDF
No ratings yet
Thread
51 pages
Java Multithreading PPT (Join AICTE Telegram)
PDF
No ratings yet
Java Multithreading PPT (Join AICTE Telegram)
37 pages
Thread: Tanjina Helaly
PDF
No ratings yet
Thread: Tanjina Helaly
38 pages
Java Threads
PDF
No ratings yet
Java Threads
44 pages
(AJP) Chapter 3
PDF
No ratings yet
(AJP) Chapter 3
32 pages
By Asst. Professor Dept. of Computer Application ST - Joseph's College (Arts & Science) Kovur, Chennai
PDF
No ratings yet
By Asst. Professor Dept. of Computer Application ST - Joseph's College (Arts & Science) Kovur, Chennai
29 pages
Chapter Four Java Threads
PDF
No ratings yet
Chapter Four Java Threads
43 pages
82a13409-12a1-42ac-9b6d-900f058a2657
PDF
No ratings yet
82a13409-12a1-42ac-9b6d-900f058a2657
62 pages
Thread: Presented By:-Manmeet
PDF
No ratings yet
Thread: Presented By:-Manmeet
47 pages
Multithreaded Programming
PDF
No ratings yet
Multithreaded Programming
37 pages
Java Multi Threading
PDF
No ratings yet
Java Multi Threading
37 pages
Java Unit IV
PDF
No ratings yet
Java Unit IV
18 pages
20ES3102 Java Programming Unit III Chapter 3 Multithread Programming
PDF
No ratings yet
20ES3102 Java Programming Unit III Chapter 3 Multithread Programming
17 pages
java unit-4
PDF
No ratings yet
java unit-4
18 pages
Chapter 10 - Multi-Threading in Java
PDF
No ratings yet
Chapter 10 - Multi-Threading in Java
29 pages
20CS6205 Fund. of JAVA Programming UNIT-IV
PDF
No ratings yet
20CS6205 Fund. of JAVA Programming UNIT-IV
28 pages
Threads
PDF
No ratings yet
Threads
43 pages
Multi Threading
PDF
No ratings yet
Multi Threading
158 pages
UNIT 4 - multithreading
PDF
No ratings yet
UNIT 4 - multithreading
42 pages
MULTITHREADING IN JAVA
PDF
No ratings yet
MULTITHREADING IN JAVA
50 pages
Multi ThreadingUpdated
PDF
No ratings yet
Multi ThreadingUpdated
45 pages
Chapter One Moti
PDF
No ratings yet
Chapter One Moti
32 pages
Multithreading
PDF
No ratings yet
Multithreading
43 pages
Multithreading and Generic Programming
PDF
No ratings yet
Multithreading and Generic Programming
58 pages
Thread - 1
PDF
No ratings yet
Thread - 1
25 pages
UNIT-5 new
PDF
No ratings yet
UNIT-5 new
46 pages
Thread Programming
PDF
No ratings yet
Thread Programming
8 pages
Lab 2 - Threads
PDF
No ratings yet
Lab 2 - Threads
7 pages
Unit1
PDF
No ratings yet
Unit1
73 pages
Java Unit - IV
PDF
No ratings yet
Java Unit - IV
48 pages
Thread
PDF
No ratings yet
Thread
20 pages
Chapter 2 - Unit 3
PDF
No ratings yet
Chapter 2 - Unit 3
46 pages
Appletcontinues
PDF
No ratings yet
Appletcontinues
47 pages
0b6at Wuxbp6ldWN1RWt6ZS1oWnZvbk5qTFYwdHVSSGxWYkV3
PDF
No ratings yet
0b6at Wuxbp6ldWN1RWt6ZS1oWnZvbk5qTFYwdHVSSGxWYkV3
40 pages
Java Multi-Threading
PDF
No ratings yet
Java Multi-Threading
45 pages
Threads Synchronization
PDF
No ratings yet
Threads Synchronization
29 pages
Threads in Python Programming
PDF
No ratings yet
Threads in Python Programming
30 pages
CH 6
PDF
No ratings yet
CH 6
91 pages
JAVA 11 MultithreadedProgramming
PDF
No ratings yet
JAVA 11 MultithreadedProgramming
92 pages
Chapter 3 (2)
PDF
No ratings yet
Chapter 3 (2)
40 pages
Thread
PDF
No ratings yet
Thread
24 pages
Multi-Threading in Java
PDF
No ratings yet
Multi-Threading in Java
13 pages
E-Notes_790_Content_Document_20240917091004PM
PDF
No ratings yet
E-Notes_790_Content_Document_20240917091004PM
40 pages
AR20 JP Unit-4
PDF
No ratings yet
AR20 JP Unit-4
45 pages
Chapter 7 Multithreading Programming PDF
PDF
No ratings yet
Chapter 7 Multithreading Programming PDF
64 pages
Tasks and Multithreading
PDF
No ratings yet
Tasks and Multithreading
37 pages
Thrad Life
PDF
No ratings yet
Thrad Life
12 pages
M8-Threads - 2.0
PDF
No ratings yet
M8-Threads - 2.0
20 pages
(IJCST-V3I2P5) : Nikita Goel, Vijaya Laxmi, Ankur Saxena
PDF
No ratings yet
(IJCST-V3I2P5) : Nikita Goel, Vijaya Laxmi, Ankur Saxena
8 pages
Unit 4
PDF
No ratings yet
Unit 4
40 pages
Experiment 7
PDF
No ratings yet
Experiment 7
21 pages
Advanced Programming-unit 1
PDF
No ratings yet
Advanced Programming-unit 1
48 pages
MULTITHREADING
PDF
No ratings yet
MULTITHREADING
37 pages
Multithreading Programming:: Unit 3: Multithreading and Event Handling
PDF
No ratings yet
Multithreading Programming:: Unit 3: Multithreading and Event Handling
15 pages
Java Threads - Tutorial
PDF
100% (2)
Java Threads - Tutorial
10 pages
10 Multithreading
PDF
No ratings yet
10 Multithreading
50 pages
Banking Awareness_banking Awareness Topics (1)
PDF
No ratings yet
Banking Awareness_banking Awareness Topics (1)
104 pages
Applet
PDF
No ratings yet
Applet
6 pages
Nov 1-30
PDF
No ratings yet
Nov 1-30
68 pages
4 TH Sem Telugu
PDF
0% (1)
4 TH Sem Telugu
80 pages
A PPT On Cyber Security & Crime
PDF
No ratings yet
A PPT On Cyber Security & Crime
12 pages
Ilovepdf Merged
PDF
100% (1)
Ilovepdf Merged
165 pages
Motivation
PDF
No ratings yet
Motivation
18 pages