0% found this document useful (1 vote)
94 views

Java Multithreading

This document provides an overview of multithreading in Java. It defines key concepts like multitasking, multithreading, concurrency and parallelism. It explains how threads are created using the Thread class in Java and how to define the run() method. It also covers exception handling keywords like try, catch, finally and throws and categorizes exceptions into checked and unchecked exceptions. The document includes examples of handling exceptions and illustrates the exception hierarchy in Java.

Uploaded by

Joel Hubahib
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
94 views

Java Multithreading

This document provides an overview of multithreading in Java. It defines key concepts like multitasking, multithreading, concurrency and parallelism. It explains how threads are created using the Thread class in Java and how to define the run() method. It also covers exception handling keywords like try, catch, finally and throws and categorizes exceptions into checked and unchecked exceptions. The document includes examples of handling exceptions and illustrates the exception hierarchy in Java.

Uploaded by

Joel Hubahib
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

Tutorial

MutliThreading

www.btechsmartclass.com
Introduction
Every java application runs with the concept of threads or multithreading

Thread is a part of a program which can execute individually

Executing multiple threads simultaneously is


Multithreading
Introduction
To understand Multithreading concept we should know the following…

What is Multitasking?

What is Multithreading?

What is Concurrency?

What is Parallelism?
Introduction
What is Multitasking?
It is the ability to perform multiple jobs concurrently. That is
running multiple programs concurrently
Introduction
What is Multithreading?
MS Word Spell Checking
It is referred as multiple threads which are controlled by a single program.
Every program in java can run multiple threads.
Word suggestion in mobile
Playlist in MediaPlayer
Video Games
Introduction
What is Concurrency?
It is the process of executing multiple processes simultaneously
on a single CPU

What is Parallelism?
It is the process of executing multiple processes simultaneously
on individual CPUs
Thread
Definition: A part of the program which can run individually

public File Downloader(String url) What happens if I want to download 4 File?


{
Code for downloading a file - Execute the program for 4 times
-
- - Create 4 objects and call the method
return File; one after the other
}

The threads concept makes it easy


Thread
When a java program is executed automatically a thread is
created known as main thread by Java-Runtime system
In java, every thread is created with the help of built-in class

Thread
which is in the

java.lang
package
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Creating
Thread
Create an object of Thread class
Thread t = new Thread( ) ;
Override run() method with the code to be run by that thread
public void run( ){
Code to be run by the
thread
…..
}
Call the run( ) method using start( ) method
t . Start( );
Concept
Exception handling will not corrects the runtime error, but
just informs the user by providing some information about
that error.
Reasons
An exception can occur for many different reasons,
including the following….
A user has entered invalid data

A file that needs to be opened cannot be found

A network connection has been lost in the middle of


communications or the JVM has run out of memory

Physical problem like device not working, cable related problem


Handling
Exceptions
To handle an exception in java we use the following
keywords…
1 try

2 catch

3 finally

4 throw

5 throws
Handling
Exceptions
To handle an exception in java we use the following
keywords…
1 try

2 catch
The try keyword3
is used
finally
to define a
block of statements which may
4 throw
generate exception
5 throws
Handling
Exceptions
To handle an exception in java we use the following
keywords…
2 catch

1 to define
The catch keyword is used try a block of
statements which can handle the exception occurred
in try block 3 finally

4 atleast
Every try block must have throwone catch block

The try block may have5multiple catch


throws blocks
Handling
Exceptions
To handle an exception in java we use the following
keywords…
3 finally

1 try
The finally keyword is used to a
2
block of statementscatch
which must be
execute irrespective
4 of Exception
throw
occurance.
5 throws
Handling
Exceptions
To handle an exception in java we use the following
keywords…
4 throw

1 try

2 catch is used to
The throw keyword
throw an exception
3 finallyexplicitly.

5 throws
throw
Keyword
import java.io.*;
Example class ThrowDemo{
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println(“Enter any two Integer values”);
int a = input.nextInt();
int b = input.nextInt();
try{
if(b == 0)
throw new Exception(“Can not divide!!!”);
int result = a / b;
System.out.println(“Result of a / b = ”+result);
}
catch(Exception e){
System.out.println(e);
}
}
}
Handling
Exceptions
To handle an exception in java we use the following
keywords…
5 throws

1 try
The throws keyword
2
is
catch
used to list
the types of Exceptions that a
3 finally
method might throw.
4 throw
throws
Keyword
class ThrowsDemo {
void myMethod(int n) throws IOException,ClassNotFoundException {
Example if(n ==1)
throw new IOException(“Message 1 !!!”);
else
throw new ClassNotFoundException(“Message 2 !!!”);
}
}
class ThrowsDemoTest {
public static void main(String args[]) {
ThrowsDemo obj = new ThrowsDemo();
try{
obj.myMethod(1);
}
catch(Exception e){
System.out.println(e);
}
}
}
Categories
In java there are TWO types of exceptions

Checked Exceptions
The checked exceptions are checked at compile-time

Unchecked Exceptions
The unchecked exceptions are checked at runtime
Checked
Exceptions
Checked exceptions should handle the exception using
try - catch block or it should declare the exception
using throws keyword, otherwise the program will give a
compilation error.

IOException
SQLException
DataAccessException
ClassNotFoundException
Checked
Exceptions
Example
import java.io.*;
class Example {
public static void main(String args[]) {
FileInputStream fis = new FileInputStream("B:/myfile.txt");
/*This constructor FileInputStream(File filename) throws FileNotFoundException */
int k;
while(( k = fis.read() ) != -1) {
System.out.print((char)k);
}
fis.close();
/*The method close() closes the file input stream * It throws IOException*/
}
}
Unchecked
Exceptions
Unchecked Exceptions mostly arise due to programming
errors like accessing method of a null object, accessing
element outside an array bonding or invoking method with
illegal arguments etc,.

NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException
Exception
Hierarchy
In java all the Exceptions are defined as Classes to handle
them. All those classes are in following hierarchy…
Throwable

Error Exception

RunTimeException IOException SQLException

NullPointerException
IndexOtOfBoundsException
NumberFormatException
…..
Exception
Hierarchy
Exception
Hierarchy
Creating
Exceptions
To create your own exception types to handle situations just define a
subclass of Exception
class MyOwnException extends Exception {
public MyOwnException(String msg){
super(msg);
}
}
class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try { employeeAge(-2); }
catch (MyOwnException e){ e.printStackTrace(); }
}
}

You might also like