0% found this document useful (0 votes)
81 views23 pages

Java - UNIT IV

The document covers multithreaded programming in Java, explaining the concept of threads, their lifecycle, and methods for creating and managing them. It also discusses error and exception management, detailing compile-time and run-time errors, as well as the handling of exceptions in Java. Key concepts such as thread synchronization, priority, and common exceptions are also addressed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views23 pages

Java - UNIT IV

The document covers multithreaded programming in Java, explaining the concept of threads, their lifecycle, and methods for creating and managing them. It also discusses error and exception management, detailing compile-time and run-time errors, as well as the handling of exceptions in Java. Key concepts such as thread synchronization, priority, and common exceptions are also addressed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

III B.

Sc CS Java Programming Siri PSG Arts & Science College for


Women

UNIT – IV

4.1 MULTITHREADED PROGRAMMING


4.1.1 INTRODUCTION:
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
 Multitasking  Execute several programs simultaneously. In system terminology it is called
multithreading.
 Multithreading  A program is divided into two or more subprograms, which can be implemented at
the same time in parallel.
 A thread is similar to a program that has single flow of control. It has a beginning, a body, and an
end and executes commands sequentially. All main programs can be called as single threaded
programs.
 Java enables us to use multiple flows of control in developing programs. Each flow of control may
be thought of as a separate tiny program known as a thread that runs in parallel to others.
 A program that contains multiple flows of control is known as multithreaded program.
 Advantages of thread
 It increases the speed of execution.
 It allows to run more tasks simultaneously
 It reduces the complexity of the program.
 It maximizes the CPU utilization.

4.1.2 CREATING A THREAD


 Threads are implemented in the form of objects that contain a method called run ( ). The run ( )
method is the heart and soul of any thread.
Syntax:
public void run ( )
{
---
---
}
 The run ( ) method should be invoked by an object of the concerned thread.
 This can be achieved by creating the thread and initiating it with the help of another thread method
called start ( ).

1
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 The run ( ) method should be invoked by an object of the concerned thread.

A new thread can be created in two ways:


 By creating a thread class: Define a class that extends thread class and override its run ( ) method
with the code required by the thread.
 By converting a class to a thread: Define a class that implements Runnable interface. The
Runnable interface has only one method, run ( ), this is to be defined in the method with the code to
executed by the thread.

4.6.3 LIFE CYCLE OF A THREAD


 The life cycle of a thread consists of the following states:
 New born state
 Runnable state
 Running state
 Blocked state
 Dead state
A Thread is always in one of these five states. It can move from one state to another via a variety of
ways.

Newborn
New thread

Start

Running Runnable
Active Thread Stop
stopyield Dead Killed thread

sleep, wait, suspend resume, stop


notify
Blocked
Idle thread
(Not Runnable)

Fig: State transition diagram of a thread


 Newborn state:
Creation of thread object is said to be in newborn state. The thread is not yet scheduled for running.
At this state, we can do only one of the following things with it:
 Schedule it for running using start( ) method.
2
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Kill it using stop( ) method.

New born

start stop
Runnable State Dead state

Fig: Scheduling a newborn thread

Runnable state:
 The runnable state, the thread is ready for execution and is waiting for the availability of the
processor.
 If all threads have equal priority, then they are given time slots for execution in round robin fashion,
i.e., first-come, first-serve manner.
 The thread that relinquishes control joins the queue at the end and again waits for its turn. This
process of assigning time to threads is known as time-slicing.
 Yield () method is used to relinquish control from one thread to another of equal priority.
yield

Running ...... ………… .


Thread
Runnable thread
Fig: Relinquishing control using yield ( ) method
 Running state:
 Running means that the processor has given its time to the thread for its execution. The thread runs
until it relinquishes control on its own or it preempted by a higher priority thread.
 A running thread may relinquish its control in one of the following situations:
 It has been suspended using suspend ( ) method. A suspended thread can be revived by using the
resume ( ) method.
suspend

resume

Running Runnable Suspended

3
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Fig: Relinquishing control using suspend ( ) method
 It has been made to sleep. To sleep a thread sleep (time) method is used, when time is in
millisecond. The thread re-enters the runnable state as soon as this time period is elapsed.

sleep ( t )

after (t)

Running Runnable Sleeping


Fig: Relinquishing control using sleep( ) method

 It has been told to wait until some event occurs. This is done using the wait ( ) method. The
thread can be scheduled to run using the notify ( ) method.

wait

notify

Running Runnable Waiting


Fig: Relinquishing control using wait ( ) method

 Blocked state:
 A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state.
 A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.
 Dead state:
 Every thread has a life cycle. A running thread ends its life when it has completed executing its run( )
method. It is a natural death.
 A thread can be killed as soon it is born, or while it s running, or even when it is in “not runnable”
condition.

4.6.4 USING THREAD METHODS


 The Thread class has methods that can be used to control the behavior of threads. There are two
constructors in thread class

4
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 public Thread(String threadName)
 public Thread()
1. start() method
This method is used to start a new thread. When this method is called the thread enters the ready to
run mode and this automatically invokes the run( ) method .
Syntax
void start( )
2. run() method
This method is the important method in the thread and it contains the statements that are to be
executed in our program. It should be overridden in our class, which is derived from Thread class.
Syntax
void run( )
{
//Statements implementing thread
}

3. sleep() method
This method is used to block the currently executing thread for the specific time.
Syntax
void sleep(time in milliseconds )

4. interrupted() method
This method returns true if the thread has been interrupted
Syntax
static boolean interrupted( )

5. isAlive() method
This method returns true if the thread is running.
Syntax
boolean isAlive( )

6. stop() method
This method is used to stop the running thread.
Syntax
void stop()

5
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

7. wait() method
This method is used to stop the currently executing thread until some event occurs
Syntax
void wait()

8. yield() method
This method is used to bring the blocked thread to ready to run mode.
Syntax
void yield()

9. setPriority( ) method
This method is used to set the priority of the thread.
Syntax
void setPriority(int P)

10. getPriority( ) method


This method is used to get the priority of the thread.
Syntax
int getPriority( )

4.6.5 THREAD EXCEPTIONS


 The sleep( ) method is enclosed in a try block and followed by a catch block. This is necessary
because the sleep ( ) method throws an exception, which should be caught.
 If we fail to catch the exception, program will not compile.
 Java run system will throw IllegalThreadStateException whenever we attempt to invoke a method
that a thread cannot handle in the given state.
 Whenever we call a thread method that is likely to throw an exception, we have to supply an
appropriate exception handler to catch it.
 The catch statement may take one of the following forms:

catch (ThreadDeath e)
{
--- // Killed thread
}

6
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
catch (InterruptedException e)
{
--- // Cannot handle it in current state
}
catch (IllegalArgumentException e)
{
--- // Illegal method argument
}
catch (Exception e)
{
----- // Any other
}

4.6.6 THREAD PRIORITY


 It affects the order in which the thread is scheduled for running. To set the priority of a thread using
the setPriority( ) method as follows:

ThreadName.setPriority(intNumber);

 The number is an integer value to which the thread’s priority is set. The thread class defines several
priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
 The integer value may assume one of these constants or any value between 1 and 10. For a thread of
lower priority to gain control, one of the following things should happen:
 It stops running at the end of run( ).
 It is made to sleep using sleep( ).
 It is told to wait using wait( ).
 If another thread of a higher priority comes along, the currently running thread will be preempted by
the incoming thread thus forcing the current thread to move to the runnable state. The highest
priority thread always preempts any lower priority threads.

7
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
4.6.7. SYNCHRONIZATION
 One thread may try to read a record from a file while another is still writing to the same file. These
produce strange results.
 To overcome the problem a technique called synchronization is used. It solve by keeping a watch on
such locations.
 The methods that will read information from a file and the method that will update the same file may
be declared as synchronized.
synchronized void update ( )
{
---- // code here is synchronized
----
}
 Java creates a “monitor”, a monitor is like a key and the thread holds the key can only open the lock.
It is possible to mark a block of code as:

synchronized (lock-object)
{
---- // code here is synchronized
----
}
 Whenever a thread has completed its work by using synchronized method, it will hand over the
monitor to the next thread that is ready to use the same resource.
 Deadlock  When two or more threads are waiting to gain control of a resource that does not
happen.
 Example, The ThreadA must access method1 before it can release method2, but the ThreadB cannot
release method1 until it gets hold on method2. Because these are mutually exclusive conditions, a
deadlock occurs.
ThreadA
synchronized method2( )
{
synchronized method1( )
{
-------
}
}
ThreadB

8
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
synchronized method1( )
{
synchronized method2( )
{
-------
}
}

_________________________________END OF UNIT IV______________________________________________

UNIT – V

5. MANAGING ERRORS AND EXCEPTIONS


5.1 INTRODUCTION
 A mistake might lead to an error causing the program to produce unexpected results. Errors are the
wrongs that can make program go wrong.
 An error may produce an incorrect output or may terminate the execution of the program abruptly or
even cause the system to crash.

5.2 TYPES OF ERRORS


 It can be broadly classified into two categories. They are:
 Compile-time errors.
 Run-time errors
 Compile-time errors:
 All syntax errors will be declared and displayed by the java compiler and therefore these errors are
known as compile-time errors.
 Whenever the compiler displays an error, it will not create the .class file. Most of these errors are
occurred by typing mistakes.
 Most common problems are:
 Missing semicolons
 Missing brackets in classes and methods
 Missing double quotes in strings
 Use of undeclared variables

9
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Incompatible type in assignments/ initialization
 Bad references to objects
 Use of = in place of == operator.
Example: The following message will be displayed
class Error
Error1.java:7: ‘;’ expected
{ System.out.println(“Hello Java “)
public static void main(String a[ ]) ^
{ 1 error

System.out.println(“Hello Java “)
}
}

 Other errors may encounter are related to directory paths. An error such as
javac: command not found  It remains to set the path correctly.

 Run-Time Errors:
 A program may compile successfully creating the .class file but may not run properly. Such programs
may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow.
 Most common run-time errors are:
 Dividing an integer by zero.
 Accessing an element that is out of bounds of an array.
 Trying to store a value into an array of an incompatible class or type.
 Trying to cast an instance of a class to one of its subclasses.
 Passing a parameter that is not in a valid range or value for a method.
 Trying to illegally change the state of a thread.
 Attempting to use a negative size for an array.
 Converting invalid string to a number.
 Using a null object reference as a legitimate object reference to access a method or a variable.
 Accessing a character that is out of bounds of a string.
Example:
class error
{
public static void main(String args[])
{
int a = 10;
int b = 10;
10
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
int c = 10;
int x = a / (b-c); // division by zero
System.out.ptinrln (“x= “ +x);
int y = a / (b+c);
System.out.println (“y= “+y);
}
}
Error message:
java.lang.ArithmeticException: / by zero at error2.main (error2.java: 10).
Java run-time tries to execute a division by zero, it generates an error condition.

5.3 EXCEPTION
 Exception is a condition that is caused by a run-time error in the program. It can be generated by the
Java run-time system, or they can be manually generated by our code.
 The error handling code that performs the following tasks:

1. Find the problem (Hit the exception)


2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exceptions)
 The error handling code basically consists of two segments; one to detect errors and to throw exception
and the other is to catch exceptions and to take appropriate actions.
Common java exceptions

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexed
ArrayStoreException Caused when a program tries to store the wrong type data in an array.
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures, such as inability to read from a file.

NullPointerException Caused by referencing a null object


NumberFormatException Caused when a conversion between strings and number fails.
OutOfMemoryException Caused when there’s not enough memory to allocate a new object.
SecurityException Caused when an applet tries to perform an action not allowed by the

11
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
browser’s security settings.
StackOverflowException Caused when the system runs out of stack space.
StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent character
position in a string.

 The error handling code basically consists of two segments, one to detect errors and to throw
exceptions and the other to catch exceptions and to take appropriate actions.
 Java exception handling is managed via five keywords: try, catch, throw, throws and finally.
 The general form of an exception handling block:
try{
// block of code to monitor for errors
}

catch (ExceptionType1 exOb){


// exception handler for exception Type1
}
catch (ExceptionType2 exOb){
// exception handler for exception Type2
}
//…..
finally( ){
// block of code to be executed after try block ends
}

5.4 MULTIPLE CATCH STATMENTS


 It is possible to have more than one catch statement in the catch block as illustrated below:
……………
……………
try
{
statement; // generates an exception
}
catch (Exception-Type-1 e)
{
statement; // processes exception type 1
}
12
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
catch (Exception-Type-2 e)
{
statement; // processes exception type 2
}
.
.
catch (Exception-Type-N e)
{
statement; // processes exception type N
}
…………….
…………….

Example:
Class Error4
{
public static void main (String args[ ])
{
int a[ ] = { 5, 10 };
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch (ArithmeticException e)
{
System.out.println(“Divison by zero”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch (ArrayStoreException e)
{
System.out.println(“Wrong data type”);

13
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
}
int y = a[1] / a[0];
System.out.println (“y =” + y);
}
}

Output:
Array Index error
Y=2

5.5 USING FINALLY STATEMETNS


 Java support another statement known as finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements.
 Finally block can be used to handle any exception generated within a try block.
 It may be added immediately after the try block or after the last catch block.

(i) try
{
…………….
……………
}
finally
{
……………..
……………..
}

(i) try
{
…………
…………
catch(………)

14
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
{
……………
……………
}
catch(……)
{
…………..
…………..
}
.
.
.
.
finally
{
…………..
……….....
}

5.6 THROWING OUR OWN EXCEPTIONS


 There may be times when we would like to throw our own exceptions.
 We can do this by using the keyword throw as follows:

throw new Throwabl’e subclass;

 Examples:
throw new ArithmeticException( );
throw new NumberFormatException( );
 The following Program demonstrates the use of a user-defined subclass of Throwable class.
 Note that Exception is a subclass of Throwable and therefore MyException is a subclass of
Throwable class. An object of a class that extends Throwable can be thrown and caught.
Example
import java.lang.Exception;
class MyException extends Exception

15
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
{
MyException(String message)
{
super (message):
}
}
class TestMyException
{
public static void main(Strings args[ ))
{
int x= 5, y= 1000;
try
{
float z =(float) x / (float) y ;
if(z < 0.01)
{
throw new MyException(“Number is too small”);
}
catch (MyException e)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage( ) );
} Output:
finally
Caught my exception
{ Number is too small
System.out.println(“ I am always here”): I am always here
}
}
}

5.7 APPLET PROGRAMMING


5.7.1 INTRODUCTION
♪ Applets are small applications that are accessed on an Internet server, transported over the Internet,
automatically installed, and run as part of a Web document

16
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
♪ They can be transported over the internet from one computer to another and run using the applet
viewer or any web browser that support the java program.
♪ It can perform arithmetic operations, display graphics, play sounds, accept user input, create
animation & play interactive games.
♪ A web page contain simple text or a static image but also a java applet which, when run, can produce
graphics, sounds and moving image.

5.7.2 BUILDING APPLET CODE


 The applet code uses the services of two classes namely Applet and Graphics from the java class
library.
 The Applet class which is contained in the java.applet package provides life and behavior to the
applet through its methods such as init(), start() and paint().
 Java calls the main() method directly to initiate the execution of the program, when an applet is
loaded, java automatically calls a series of Applet class methods for starting, running, and stopping
the applet code.
 The applet class therefore maintains the lifecycle of an applet.
 The Paint() method of the applet class, when it is called, actually displays the result of the applet
code on the screen.
 The output may be text, graphics, or sound.
 The Paint() method, which requires a Graphics object as an argument is defined:

Public void paint(Graphics g)

 This requires that the applet code imports the java.awt package that contains the Graphics class.
import java.awt.*;
import java.applet.*;
…………
………….
Public class appletclassname extends Applet
{
……………..
…………….
Public void paint(Graphics g)
{
……………..
…………….. //applet operations code
}
17
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
……………
}
 The appletclassname is the main class for the applet.
 When the applet is loaded, java creates an instance of this class, and then a series of Applet class
methods are called on that instance to execute the code.
Example :
import java.awt.*;
import java.applet.*;
Public class HelloJava extends applet
{
public void paint(Graphics g)
{
g.drawString(“HelloJava”,10,100);
}
}
 Remember the Applet class itself is a subclass of Panel class, which is again a subclass of the
Container class and so on as shown in following fig.

Fig: Chain of classes inherited by Applet class

5.7.3 APPLET LIFE CYCLE


 Every Java applet inherits a set of default behaviors from the Applet class. The applet state includes:
 Born or initialization state
 Running state
 Idle state

18
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 Dead or destroyed state

Begin Born Initialization


(Local Applet)

start ( ) stop( )
Running Idle
Stopped

Display paint( ) start( ) destroy( )


Dead

Destroyed End
Exit of browser

Fig: An applet’s state transition diagram


 Born or initialization state:
Applet enters the initialization state when it is first loaded .This is achieved by calling init( ) method of
the applet class. This applet is born. It occurs only once in the applet life cycle.
Stages:
G.F : public void init()
 Create objects needed by the applet. {
 Set up initial values. …….
…….. // action
 Load images or fonts. }
 Setup colors.

 Running state:
Applet enters the running state when the system calls the start ( ) method of the applet class. This
occurs automatically after the applet is initialized.
The Starting can also occur if the applet is already in the idle stopped state. The start( ) method may
be called by more than one time.
G.F: public void start( )
{
------
}
 Idle or stopped state:

19
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
The applet enters the idle state when it is stopped from running. Stopping occurs automatically by
invoking the destroy( ) method.
Also call the stop ( ) method explicitly. If we use the thread to run the applet then we must use the
stop ( ) method to terminate the thread. We can achieve by overriding the stop ( ) method.
G.F: public void stop( )
{
--------
}

 Dead state:
An applet is said to be in dead state when it is removed from the memory. This occurs automatically
by invoking the destroy ( ) method. It occurs only once in the applets life cycle. This method is used to
clean up the resources.
G.F: public void destroy( )
{
------
}

 Display state:
Applet moves to the display state whenever it has to perform some output operation on the screen.
This happens immediately after the applet enters into the running state. The paint ( ) method is called to
accomplish this task. Almost every applet will have a paint ( ) method like other method in the life cycle.
G.F: public void paint(Graphics s)
{
//ACTIONS
}
It is inherited from the component class, a super class of applet.

5.7.4 CREATING AN EXECUTABLE APPLET:


 Executable applet is nothing but the .class file of the applet, which is obtained by compiling the source
code of the applet.
 Take the Example program Hellojava.java, here are the steps required for compiling the HelloJava
applet.
1. Move to the directory containing the source code and type the following command
javac Hellojava.java
2. The compiled output file called Hellojava.class is placed in the same directory as the source.

20
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
3. If any error message is received then we must check for errors, correct them and compile the
applet again.

5.7.5 DESIGNING A WEB PAGE


 Java applets are programs that reside on Web pages.
 A Web page is basically made up of text and HTML tags that can be interpreted by a Web browser
or an applet viewer.
 A Web page is also known as HTML page or HTML document.
 Web pages are stored using a file extension .html such as Myapplet.html.
 Web pages include both text that we want to display and HTML tags(commands) to web browsers.
 A web page is marked by an opening HTML tag <HTML> and a closing HTML tag</HTML> & is
also divided into three major sections.

i. Comment section(optional)
ii. Head Section(Optional)
iii. Bode section

 Comment Section:
 This section contains comments about the Web page.
 It is important to include comments that tell us what is going on in the Web page.
 A comment line begins with a <! And ends with a>.
 Head Section:
 The head section is defined with a starting <HEAD> tag and a closing </ HEAD> tag.
<HEAD>
<TITLE> Welcome to Java Applets </TITLE>
</HEAD>

<HTML>

<! Comment Section


………………………………..
………………………………...
>

<HEAD>
21

</HEAD>
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women

Title Tag
Head Section

<BODY>

Body Section
Applet Tag

</BODY>

Fig: A Web page template


 Note that tags <….> containing HTML commands usually appear in pairs such as <HEAD> and
</HEAD> and <TITLE> and </TITLE>.
 A slash (/) in a tag signifies the end of that tag section

 BODY SECTION:
 After the head section comes the body section.
 This section contains the entire information about the web page and its behaviour.
<BODY>
<CENTER>
<H1> Welcome to the World of Applets </H1>
</CENTER>
<BR>
<APPLET ….>
</APPLET>
</BODY>
 The <CENTER> tag makes sure that the text is centered and <H1> tag causes the text to be of the
largest size.
 The other heading tags <H2> to <H6> to reduce the size of letters in the text.

5.7.6 RUNNING THE APPLET:


 Applet files created as well as the HTML file containing the applet, we must have the following
files in our current directory.

22
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
 HelloJava.java
 HelloJava.class
 HelloJava.html
 To run an applet, we require one of the following tools :
o Java-enabled Web Browser(such as HotJava or Netscape)
o Java appletviewer.
 If we use a java-enabled web browser we will be able to see the entire web page containing the
applet.
 If we use the appletviewer tool we will only see the applet output.
 The appletviewer is available as part of the java Development Kit.
Appletviewer HelloJava.html
 The argument of the appletviewer is not the .java file or the .class file, but rather .html file.

Applet Viewer: HelloJava.class

Applet

Hello Java

appletloader.started

Fig: Output of HelloJava applet by using appletviewer

23

You might also like