The document provides an overview of multithreaded programming in Java, explaining the concept of threads, their lifecycle, and methods for creating and managing them. It also covers synchronization, error handling, and exception management in Java, detailing the use of try-catch blocks, the throw and throws keywords, and the importance of the finally block. Additionally, it includes examples to illustrate these concepts in practice.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
8 views75 pages
Chavan CH-4.2
The document provides an overview of multithreaded programming in Java, explaining the concept of threads, their lifecycle, and methods for creating and managing them. It also covers synchronization, error handling, and exception management in Java, detailing the use of try-catch blocks, the throw and throws keywords, and the importance of the finally block. Additionally, it includes examples to illustrate these concepts in practice.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75
Multithreaded Programming ,
Managing Errors and Exceptions
Multithreading in Java
• Multithreading in java is a process of executing multiple
threads simultaneously. • A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. • However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. • Java Multithreading is mostly used in games, animation, etc. What is Thread in java • A thread is a lightweight subprocess, the smallest unit of processing. • It is a separate path of execution. • Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. • It uses a shared memory area.
• As shown in the above figure, a thread
is executed inside the process. • There is context-switching between the threads. • There can be multiple processes inside the OS, and one process can have multiple threads. Life cycle of a Thread (Thread States) • A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state. • But for better understanding the threads, we are explaining it in the 5 states. • The life cycle of the thread in java is controlled by JVM. The java thread states are as follows: • New • Runnable • Running • Non-Runnable (Blocked) • Terminated 6)The yield() - method of thread class causes the currently executing thread object to temporarily pause and allow other threads to execute. How to create thread
• There are two ways to create a thread:
• By extending Thread class • By implementing Runnable interface. Commonly used methods of Thread class: The Main Thread
• When a Java program starts up, one thread
begins running immediately. • This is usually called the main thread of your program, because it is the one that is executed when your program begins. • The main thread is important for two reasons: • It is the thread from which other “child” threads will be spawned. • Often it must be the last thread to finish execution because it performs various shutdown actions. // Create a second thread by extending Thread try {for(int i = 5; i > 0; i--) { class NewThread extends Thread { System.out.println("Main Thread: " NewThread() { + i); // Create a new, second thread Thread.sleep(1000); super("Demo Thread"); } System.out.println("Child thread: " + this); } catch (InterruptedException e) { start(); // Start the thread } System.out.println("Main thread // This is the entry point for the second thread. interrupted."); public void run() { } try { System.out.println("Main thread for(int i = 5; i > 0; i--) { exiting."); System.out.println("Child Thread: " + i); }} Thread.sleep(500); Child thread: Thread[Demo Thread,5,main] Main Thread: 5 } Child Thread: 5 } catch (InterruptedException e) { Child Thread: 4 System.out.println("Child interrupted."); Main Thread: 4 Child Thread: 3 } Child Thread: 2 System.out.println("Exiting child thread."); Main Thread: 3 }} Child Thread: 1 Exiting child thread. class ExtendThread { Main Thread: 2 public static void main(String args[]) { Main Thread: 1 Main thread exiting. new NewThread(); // create a new thread class ThreadDemo { // Create a second thread. By runnable Interface public static void main(String args[]) { class NewThread implements Runnable { new NewThread(); // create a new thread Thread t; try { NewThread() { for(int i = 5; i > 0; i--) { // Create a new, second thread System.out.println("Main Thread: " + i); t = new Thread(this, "Demo Thread"); Thread.sleep(1000); System.out.println("Child thread: " + t); } t.start(); // Start the thread } catch (InterruptedException e) { } System.out.println("Main thread // This is the entry point for the second thread. interrupted."); public void run() { } try { System.out.println("Main thread exiting."); for(int i = 5; i > 0; i--) { } System.out.println("Child Thread: " + i); Child thread: Thread[Demo Thread,5,main] } Main Thread: 5 Thread.sleep(500); Child Thread: 5 } Child Thread: 4 } catch (InterruptedException e) { Main Thread: 4 Child Thread: 3 System.out.println("Child interrupted."); Child Thread: 2 } Main Thread: 3 System.out.println("Exiting child thread."); Child Thread: 1 } Exiting child thread. Main Thread: 2 } Main Thread: 1 Main thread exiting. Creating Multiple Threads class MultiThreadDemo { // Create multiple threads. public static void main(String args[]) { class NewThread implements Runnable { new NewThread("One"); // start threads String name; // name of thread new NewThread("Two"); new NewThread("Three"); Thread t; try {// wait for other threads to end NewThread(String threadname) { Thread.sleep(10000); name = threadname; } catch (InterruptedException e) { t = new Thread(this, name); System.out.println("Main thread Interrupted"); System.out.println("New thread: " + t); } System.out.println("Main thread exiting.");}} t.start(); // Start the thread } New thread: Thread[One,5,main] // This is the entry point for thread. New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] public void run() { One: 5 try {for(int i = 5; i > 0; i--) { Two: 5 System.out.println(name + ": " + i); Three: 5 Thread.sleep(1000); One: 4 }} catch (InterruptedException e) { Two: 4 Three: 4 System.out.println(name + "Interrupted"); One: 3 }System.out.println(name + " exiting."); Three: 3 }} Two: 3 Priority of a Thread (Thread Priority):
• Each thread have a priority.
• Priorities are represented by a number between 1 and 10. • In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling). • But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Synchronization in Java
• Synchronization in java is the capability to
control the access of multiple threads to any shared resource. • Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why use Synchronization
• The synchronization is mainly used to
• To prevent thread interference. • To prevent consistency problem. Understanding the problem class MyThread2 extends Thread{ Table t; without Synchronization MyThread2(Table t){ this.t=t; } class Table{ public void run(){ void printTable(int n){ t.printTable(100); //method not synchronized } for(int i=1;i<=5;i++){ } System.out.println(n*i); try{ class TestSynchronization1{ Thread.sleep(400); public static void main(String args[]){ }catch(Exception e){System.out.println(e);} Table obj = new Table();//only one object } } MyThread1 t1=new MyThread1(obj); } MyThread2 t2=new MyThread2(obj); class MyThread1 extends Thread{ t1.start(); Table t; t2.start(); } } MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } //example of java synchronized method class MyThread2 extends Thread{ class Table{ Table t; synchronized void printTable(int n){//synchro MyThread2(Table t){ nized method this.t=t; for(int i=1;i<=5;i++){ } System.out.println(n*i); public void run(){ try{ t.printTable(100); Thread.sleep(400); } }catch(Exception e){System.out.println(e);} } } public class TestSynchronization2{ } public static void main(String args[]){ } Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); class MyThread1 extends Thread{ MyThread2 t2=new MyThread2(obj); Table t; t1.start(); MyThread1(Table t){ t2.start(); this.t=t; } } } public void run(){ t.printTable(5); }
} Exception Handling in Java • The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
• In this page, we will learn about Java exceptions, its type
and the difference between checked and unchecked exceptions.
What is Exception in Java
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at runtime. What is Exception Handling • Exception Handling is a mechanism to handle runtime errors such as • ClassNotFoundException • IOException • SQLException • RemoteException, etc. Common Scenarios of Java Exceptions Java try-catch block • Java try block • Java try block is used to enclose the code that might throw an exception. It must be used within the method. • If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception. • Java try block must be followed by either catch or finally block. • Java Catch block • Java catch block is used to handle the Exception by declaring the type of exception within the parameter. • The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception. • The catch block must be used after the try block only. You can use multiple catch block with a single try block. Example 7 In this example, we handle the generated exception (Arithmetic Exception) with a different type of exception class (ArrayIndexOutOfBoundsException). Java finally block • Java finally block is a block that is used to execute important code such as closing connection, stream etc. • Java finally block is always executed whether exception is handled or not. • Java finally block follows try or catch block
Why use java finally
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc. Java throw keyword
• The Java throw keyword is used to explicitly throw an
exception. • We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. • The syntax of java throw keyword is given below. • throw exception; – Let's see the example of throw IOException. • throw new IOException("sorry device error); Example 1: Throwing Unchecked Exception In this example, we have created a method named validate() that accepts an integer as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. Java throws keyword • The Java throws keyword is used to declare an exception. • It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. • Exception Handling is mainly used to handle the checked exceptions. • If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used – Syntax of java throws return_type method_name() throws exception_class_name{ //method code } • Advantage of Java throws keyword • Now Checked Exception can be propagated (forwarded in call stack). • It provides information to the caller of the method about the exception. Java throws example Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword. import java.io.IOException; class Testthrows1{ void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ Testthrows1 obj=new Testthrows1(); obj.p(); System.out.println("normal flow..."); } } • Write a program to input name and age of person and throws user defined exception, if entered age is negative. System.out.println("enter age and name of person"); import java.io.*; try { class Negative extends Exception age=Integer.parseInt(br.readLine()); { name=br.readLine(); Negative(String msg) { { if(age<0) super(msg); throw new Negative("age is negative"); } else throw new Negative("age is positive"); } } } class Negativedemo catch(Negative n) { { public static void main(String ar[]) System.out.println(n); { } int age=0; catch(Exception e) { } String name; BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in)); • Write a program to accept password from user and throw ‘Authentication failure’ exception if password is try incorrect. { System.out.println("Enter Password : "); if(bin.readLine().equals("EXAMW15")) import java.io.*; { class PasswordException extends Exception System.out.println("Authenticated "); { } PasswordException(String msg) Else { { super(msg); throw new PasswordException("Authentication failure"); } } } } class PassCheck catch(PasswordException e) { { public static void main(String args[]) System.out.println(e); { } BufferedReader bin=new BufferedReader(new catch(IOException e) InputStreamReader(System.in)); { System.out.println(e); }}}