0% found this document useful (0 votes)
25 views20 pages

Java Chapter - 06-1

The document provides an overview of multithreading in Java, explaining concepts such as multitasking, thread types, thread creation methods, and the thread lifecycle. It also covers synchronization, exception handling, and various exception types, including checked and unchecked exceptions. Additionally, it details the mechanisms for handling exceptions using try-catch blocks, throw and throws keywords, and finally blocks.
Copyright
© © All Rights Reserved
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% found this document useful (0 votes)
25 views20 pages

Java Chapter - 06-1

The document provides an overview of multithreading in Java, explaining concepts such as multitasking, thread types, thread creation methods, and the thread lifecycle. It also covers synchronization, exception handling, and various exception types, including checked and unchecked exceptions. Additionally, it details the mechanisms for handling exceptions using try-catch blocks, throw and throws keywords, and finally blocks.
Copyright
© © All Rights Reserved
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/ 20

JAVA VVFGC,TUMKUR

CHAPTER – 06
MULTITHREADING IN JAVA

What is Multi-Tasking & explain its types. 3M


 A multithreaded program contains two or more tasks can run simultaneously.
 Performing two or more task at same time is known as multi tasking

Two type of multi-tasking

Process based multitasking (PBM):-


Two or more program (processes) can run simultaneously is called PBM
Ex: - Running VLC, Scanning for virus, working with internet etc…..

Thread based multitasking (TBM)


Single program performing more than one task at the same time is known as thread based
multitasking.

Ex: - An MS word program can check the spelling of word while we type the document.
Java program make use of both process based and thread based multitasking.

What is a Thread. 1M
Thread: ”A single line of execution or process of execution”.
What is Multi-Threaded. 1M
Multithreaded=>”Multiple line of execution”

Explain the types of threads. 3M


 Daemon threads
 User threads

Daemon thread usually designed to run in the background for the purpose of servicing
user thread.

Dept. of BCA Page 1


JAVA VVFGC,TUMKUR

User thread: - The main thread is a user thread made a variable by JVM. This thread is a
launched in public static void main method. From there main thread we can create all
other threads. We already work with one particular thread since from our java first
program i.e. main thread

Explain the creation of threads. 3M


Threads can created in two different ways.

 By extending the java.lang.thread.class


 By implementing the java.lang.Runnable interface
By extending threading class: -
Define a class that extends thread class and over write run (method)

class xyz extends thread


{
public void run ()
{
System.out.println (“this is thread class extends”);
}
}
In Run () method will write the code that is require to be executed by new thread. The run
method is the core part of thread in java. This methods is entry point and exit point for any
thread we create. import java.io.*;
import java.lang.*;
{
public void run ()
{
For (i=1; i<=5; i++)
System.out.println (“thread A:”+i);
System.out.println (“exit from A”);
}
}
class B extends thread

Dept. of BCA Page 2


JAVA VVFGC,TUMKUR

{
public void run ()
{
for (i=1; i<=5; i++) System.out.println (“thread B:”+i);
System.out.println (“exit from B”);
}
}
public class Ex
{
public static void main (string args [0])
{
Aobj.1=new A ();
B obj.2=new B ();
Obj1.start ();
Obj2.start ();
}
}

Output
Thread A: 1
Thread B: 1
Thread A: 2
Thread B: 2
Thread A: 3
Thread B: 3
Thread A: 5
Thread B: 5 Exit from B Exit from A

By implementing runnable interface:-


Define a class that implements runnable interface. The runnable interface as only one method
run. This can be implemented in our class.
Syntax:-
interface runnable

Dept. of BCA Page 3


JAVA VVFGC,TUMKUR

{
public void run();
}
We can write the code for the run method in our class.
Example program: import java.io.*;
import java.lang.*;
class A implements runnable
{
public void run()
{
for (int i=1;i<=5; i++)
System.out.println (“Thread A:”+i);
System.out.println (“exit from A”);
}
}
class B implements runnable
{
public void run()
{
for(int i=1;i<=5; i++)
System.out.println (“Thread B:”+i);
System.out.println (“exit from B”);
}
}
public class Ex
{
public static void main(String args[])
{
A obj1=new A();
B obj2=new B();
Thread t1=new Thread (obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();

Dept. of BCA Page 4


JAVA VVFGC,TUMKUR

}
}

Explain the Life cycle of a Thread. 5M

Born Stage

Start()
run()
sleep() Stop()
Runnable Running
wait() Dead Stage

Stop()
Notify()

suspend() resume(

Blocked Stage

During the life time of a Thread there are many stages of a Thread can enter they are
1. Born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

1. Born state:- While creating the object for a thread class and this object is not yet
running. Thenthe Thread is new born state.
2. Runnable state :- When the start() is called the Thread object, the thread is in
the runnablestate.

Dept. of BCA Page 5


JAVA VVFGC,TUMKUR

3. Running state:- A thread currently being executed by the cpu is in the running state.
4. Blocked state:- When the thread is suspended, sleeping or waiting in order to
satisfied certainrequirement then the thread is in blocked state.
5. Dead state:- A running thread ends its life when it has computed its execution
(Run()), then it iscalled a natural death.

Explain the methods of Thread class. 3M


1. Start():- It calls the run method to being executing the Thread.
2. Stop():- To kill the Thread.
3. run():- It executes the body of the thread.
4. sleep():- It is used to move a Thread to sleep for a specified amount of a time in mile
second.
5. wait():- Waiting stage of Thread until the condition.
6. Notify():- After the condition the waiting Thread automatically execute.
7. Resume():- Resumes the execution of the Thread.
8. Suspend():- It is similar to wait when using suspend the method resume will be
taken
9. Yield():- It is used to stop the execution of a particular Thread
10. setName():- It sets the name of a Thread
11. getName():- It returns the name of a Thread
12. Current Thread ():- It returns the name of the currently executing the Thread.

Explain Thread Priorities. 3M


Thread priority is an integer value that identifies the relative order in which it should be
executed with respect to others. The Thread priority values ranging from 1 to 10 &
default value is 5. But if a Thread has highest priority does not means that will execute 1st
, the Thread scheduling depends on the operating system.

 setPriority :- It is used to set the priority that can increase the chances of the execution.(Public
t1.setPriority(10);

 getPriority: - This method returns the priority of a

Dept. of BCA Page 6


JAVA VVFGC,TUMKUR

particular Thread.Public final int getpriority ():


Ex: - int
x=t1.getPriority ():The
constant priority values
are:
public final static int
MIN_PRIORITY=1; public final
static int NORM_PRIORITY=5;
public final static int
MAX_PRIORITY=10;

PROGRAM:
import java.io.*;
import java.lang.*;
class A extends Thread
{
public void run ()
{
for(int i=1;i<=5;i++)
System.out println(“Thread A “+i);
System.out.println (“Exit from A”);
}
}
class B extends Thread
{
public void run ()
{
for (int i=1;i<=5;i++) System.out.println (“Thread B“+i);
System.out.println (“Exit from B”);
}
}
public class Ex

Dept. of BCA Page 7


JAVA VVFGC,TUMKUR

{
public static void main (String args[])
{
A obj=new A (); B obj=new B ();
obj2.setPriority (10);
obj1.setPriority (1);
obj1.setName (“1st Thread”);
obj2.setName (“2nd Thread);
obj1.start ();
obj2.start ();
System.out.println (“Thread 1 Name=”+obj1.getName ());
System.out.println (“Thread 2 Name=”+obj2.getName ());
}
}

What is Synchronization. 1M
“It is the process of avoiding multiple Thread to act on same data or method”

Synchronization is uses while execution time, the one Thread is under execution
process there is nopossibility to enter another Thread into execution.
The synchronization can be achieved in java by two ways
1. By using synchronized method
2. Synchronized block

By using synchronized method :-


The synchronized is used to synchronize the hole method
Syntax:-
Synchronized void withdrawal()
{
………
………
………

Dept. of BCA Page 8


JAVA VVFGC,TUMKUR

Synchronize block :-
Synchronized block is used to synchronize block of statement in a method
Syntax:-
Synchronized(object)
{
……..
……..
……..
}

EXCEPTION HANDLING

What is an Error & explain the types of Error. 3M


Error: “Something wrong occurs in the program”.

Basically errors are classified into 2 types.


1. Compile time errors.
2. Run time errors.

1. Compile Time Errors.


These errors are syntactical errors, found at the time of compilation by
the compiler.Ex: missing semicolon, missing flower bracket, missing
quotes etc..
2. Run Time Errors.
Sometimes JVM would be enabling to execute statements due to some reasons. These
errors arecalled as run-time errors.
Sometimes programs may produce wrong results due to wrong logic or may terminate
due to somereasons.
 Divide by zero (1/0).
 Accessing an element out of bounds of an array.
 Reading data from an already closed file.

Dept. of BCA Page 9


JAVA VVFGC,TUMKUR

What is an Exception? 1M
“An error occurs at runtime is called an Exception.”

What is Exception Handling? 1M


“The mechanism of handling runtime errors or exceptions is called Exception
handling.”

Explain the Types of Exceptions. 3M

Exception

Unchecked Exception OR Checked Exceptions OR


Run-time Exception Other Exception

Unchecked Exceptions (run-time exceptions)


The compiler doesn‟t handle the exceptions at compile- time, those exceptions are called
uncheckedexceptions. These are checked by the JVM.

Example for Unchecked Exception Classes:


 ArithmeticException
 ArrayIndexOutOfBoundsException
 ClassCastException

Checked Exception(Other Exceptions)


The compiler handles at the time of compilation,those exceptions are called Checked
Exceptions.

Example for Checked Exception Classes:


 IOException

Dept. of BCA Page 10


JAVA VVFGC,TUMKUR

 FileNotFoundException
 illegalAccessException

Exception Handling performs the following Techniques


1. Hit the Exception :- Finding the problem.
2. Throw the Exception :- Finding that error as occurred.
3. Catch the Exception :- receiving the error information.
4. Handle the Exception :- Taking Actions.

Explain the mechanism to handle the Exception. 5M


try
catch
throw throws
finally

try :
try
{
……………
…………… //java statements
}
The try block consists of a executable statements that can possible to throw exceptions
implicitly. try block throw the exceptions implicitly, if the exception occurs in this block.

catch block:
try
{
……
…… //java statements
}
catch(exception_type e)
{
……

Dept. of BCA Page 11


JAVA VVFGC,TUMKUR

……. //processing of exception


}

catch block catches the exception thrown by the try block.


 A catch block consists of the keyword catch followed by a single parameter that identify
the type of exception and „e‟ is the object for the class Exception.
 Using this object (e) we can print details of Exception.
 Exception type can be the type of exception.
 “Exception class is the super class for all other Exception class types.”
 e.getMessage() : It prints the detailed information about the Exception that as occurred.

Note: If we are using catch block, we must use try block.

Ex: import java.io.*; public class Ex


{
public static void main(String args[])
{
int d=0; try
{
System.out.println(10/d);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}

Multiple catch blocks.


Syntax: try
{
…….
…….

Dept. of BCA Page 12


JAVA VVFGC,TUMKUR

}
catch(Exception_type1 e)
{
…..
…..
}
catch(Exception_type2 e)
{
……
…….
}
We can also use multiple catch blocks to handle different types of Exceptions. If the try block
throw an Exception,that will matches the catch block Exception type and processing the
Exception in the particular catch block.

Ex: try
{
int y=a[1]/a[0]; System.out.println(“Y=”+y);
a[2]=30;
}
catch(Arithmeticexception e)
{
System.out.println(“Don‟t‟t divide by zero”);
}
catch(ArrayIndexoutOfBoundsException e)
{
System.out.println(“It is Array Index Out of Bounds”);
}
catch(ArrayStoreException e)
{
System.out.println(e.getMessage());
}
}

Dept. of BCA Page 13


JAVA VVFGC,TUMKUR

[Note: Checked Exception classes and Unchecked Exception classes see the Text book or
browse in the Internet.]

throw keyword ( clause)


The “throw” keyword is used when the programmer wants to throw an exception
explicitly and handle it using catch block.
“throw keyword is used to throw an exception explicitly.” Syntax: throw new Throwable
Exception Object;
Ex: throw new NegativearraySizeException(“Plz Enter the size”);

Constructor String parameter catch(NegativearraySizeException e)


class datatype user object

Ex:
import java.io.*;
public class Ex
{
public static void main(string args[])
{
int size;
int[] a=new int[10];
size=Integer.parseint(args[0]);
try
{
if(size<0)
throw new negativeArraySizeException(“Plz enter positive size”);
for(int i=0;i<size;i++)
a[i]=i+1;
}
catch(NegativeArraySizeException e)
{
System.out.println(e);
}
}

Dept. of BCA Page 14


JAVA VVFGC,TUMKUR

throws keyword(clause)
“The throws keyword is used when the programmer doesn‟t wants to handle the exception in
the method(inside the method) and throw it out of method.”
The method must declare it using the „throws‟ keyword. „throws‟ keyword appears at the end of
a method signature ,if multiple exceptions are there ,we can separate it with comma operator(,).

Syntax:
return_typemethod_name(parameter_list)throws Exception_type1,Exception_type2,…..

……..
……..

public class Ex
{
public static void main(String args[])throws IOException,NumberFormatException
{
…….
…….
}
}

finally block
“A finally block of code always executes whether an Exception as occurred or not.” Finally
block appears at the end of the catch block or at the end of try block.

Dept. of BCA Page 15


JAVA VVFGC,TUMKUR

try
No Exception Exception

finally catch

finally

Syntax:
try
{

}
………
……….

catch(Exception_type e)
{

…….
…….
}
finally
{

}
……..
…….. //finally block always excecutes.

Dept. of BCA Page 16


JAVA VVFGC,TUMKUR

finally block is commonly used for,


 closing a file.
 Closing a result set.
 Closing the connection established with connection. [Note: finally block is optional.]

Ex:
importjava.io.*;
public class Ex
{
public static void main(String args[])
{
int size;
int[] a=new int[10];
size=Integer.parseint(args[0]);
try
{
}
finally
{
if(size<0)
throw new NegativeArraySizeException(“Plz enter positive size”);
for(int i=0;i<size;i++)
a[i]=i+1;

System.out.println(“This is Finally Block”);


}
}
}

Explain the creation of our own Exception Classes. 3M


When we want to create an Exception class of our own, simply make your class as sub class
Exception.
Ex:

Dept. of BCA Page 17


JAVA VVFGC,TUMKUR

import java.io.*;
class Vvfgc extends NegativeArraySizeException
{
Vvfgc()
{
super(“plz enter +ve array size”);
}
}
public class Ex
{
public static void main(String args[])
{
int size;
int[] a=new int[10]; size=Integer.parseInt(args[0]);
try
{

}
if(size<0)
throw new Vvfgc();
System.out.println(“This is +ve Array Size”);

catch(Vvfgc e)
{
System.out.println(e);
}
}
}
Here we have created our own exception class called as Vvfgc, which is a sub class os
NegativeArraySizeException. By running the program with negative value, the output will
be,
Vvfgc: plz enter +ve array size.

Dept. of BCA Page 18


JAVA VVFGC,TUMKUR

Explain the features of Exception Handling in Java. 1M


 Separate error-handling code from normal code.
In traditional programming error detection, reporting and handling often makes the code
more confusing, but Java provides an easier solution to the problem of error management i.e
Exceptions.
 Propagation of Errors.
Another feature of Java Exception is the ability to propagate error reporting of the call of
methods using exception classes.
Note: *We can have nesting of try statements, which means, we can have try-catch block
within try block.
 If we keep System.exit(0); in try block, then it will not go to the finally block.

What is Collection in Java?1M


A Collection represents a single unit of objects, i.e., a group.
or
Any group of individual objects which are represented as a single unit is known as the
collection of the objects.

The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.

What is a Framework?1M

A framework is a set of classes and interfaces which provide a ready-made architecture. In


order to implement a new feature or a class, there is no need to define a framework.

Advantages of the Collection Framework:


 Consistent API
 Reduces programming effort
 Increases program speed and quality

Dept. of BCA Page 19


JAVA VVFGC,TUMKUR

Hierarchy of the Collection Framework

 Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.

 Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.

Dept. of BCA Page 20

You might also like