Java Unit IV
Java Unit IV
Unit-IV
MultiThreaded
Programming
...............
A typical run() method will have the following }
format:
Now we have a new type of thread MyThread.
public void run( )
{ 2. Implementing the run() Method:
..........
.......... The run( ) method has been inherited by the
// (statements for implementing thread) class MyThread. We have to override this
.......... method in order to implement the code to be
} executed by our thread.
The run() method should be invoked with the The basic implementation of run() will look
help of a thread method called start () by an like this:
object of the concerned thread.
public void run()
Creating Threads {
................
A new thread can be created in two ways. ................// Thread code here
1. By creating (extending) a thread class: ................
Define a class that extends Thread class and }
override its run( ) method with the code
required by the thread. When we start the new thread, Java calls the
thread’s run( ) method. So that the run() method
2. By converting a class to a thread: can perform all its given tasks.
Define a class that implements Runnable
interface. The Runnable interface has only one 3. Starting New Thread:
method, run( ), that is to be defined in the To start a new thread, first we need to create an
method with the code to be executed by the object of thread class and then we need to call
thread. it using the start () method.
For example:
Extending the Thread class
MyThread mt = new MyThread( );
We can make our class to be runnable as thread mt.start( ); // invokes run() method
by extending the class java.lang.Thread. This
gives us access to all the thread methods Example Program:
directly.
class A extends Thread
It includes the following steps: {
1. Declare the class as extending the Thread public void run( )
class. {
2. Implement the run( ) method. for (int i = 1; i < = 5; i + +)
3. Create a thread object and call the start( ) {
method. System.out.println(“\ t From Thread
A : i = ” + i);
1. Declaring the Class: }
The Thread class can be extended as follows: System. out. println(“ Exit from A “);
class MyThread extends Thread }
{ }
...............
...............
Stopping a Thread
Newborn State:
When we create a thread object, the thread is 1. It has been suspended: A running thread
born and is said to be in newborn state. At this can be suspended using suspend( )
state, we can do only one of the following method. A suspended thread can be revived
things with it: by using the resume( ) method.
• Schedule it for running using start( )
method.
• Kill it using stop( ) method.
Dead State:
A running thread ends its life when it has
completed executing its run( ) method. It is a
natural death. We can also kill a thread by
sending the stop() message to it at any state.
This causes a premature death to it. A thread
Running State: can be killed from new born state, or running
Running means that the processor has given its state, or even in blocked states.
time to the thread for its execution. A running
thread may relinquish its control in one of the
following situations:
THREAD EXCEPTIONS
The intNumber is an integer value to which the
Java run system will throw thread’s priority is set.
IllegalThreadStateException whenever we
attempt to invoke a method that a thread cannot The Thread class defines several priority
handle in the given state. constants:
MIN_PRIORITY = 1
For example, a sleeping thread cannot deal with NORM PRIORITY = 5 (Default Setting)
the resume( ) method. Because a sleeping MAX_PRIORITY = 10
thread cannot receive any instructions.
The intNumber may assume one of these
A blocked thread cannot deal with the constants or any value between 1 and 10.
suspend() method.
Most user-level processes should use
Whenever we call a thread method that is likely NORM_PRIORITY, plus or minus 1.
to throw an exception, we have to supply an
appropriate exception handler to catch it. Background tasks such as network I/ O and
screen repainting should use a value very near
The catch statement may take one of the to the lower limit.
following forms:
A highest priority thread always preempts any
catch (ThreadDeath e) lower priority threads.
{
................ Example:
................ // Killed thread
} class A extends Thread
catch (InterruptedException e) {
{ ................. public void run( )
................. // Cannot handle it in the current {
state System.out.println(“ threadA started”);
} for( int i = 1; i < = 5; i + +)
catch (Illegal ArgumentException e) {
{ ............... ............... // Illegal method System. out. println(“\t From
argument Thread A : i = ” + i);
} }
catch (Exception e) System. out. println(“ Exit from A ”);
{ ................ }
................ // Any other }
}
class B extends Thread
Thread Priority {
In Java, each thread is assigned a priority. It public void run( )
affects the order in which it is scheduled for {
running. The threads of the same priority can System.out.println(“ threadB started”);
share the processor on a first-come, first-serve for( int j = 1; j < = 5; j + +)
basis. {
Java permits us to set the priority of a thread System. out. println(“\tFrom
using the setPriority( ) method. It has the Thread B : j = ” + j );
following format: }
System. out. println(“ Exit from B ”);
ThreadName.setPriority( intNumber); }
The following Java Program causes a compile- ▪ Attempting to use a negative size for an
time error: array Converting invalid string to a
Class CompileTimeError1 number
{ ▪ Accessing a character that is out of
public static void main(String args[]) bounds of a string
{ Example: The following code generates a
System.out.println(“ Hello Java!”) runtime error.
// The above line Missing ; ( Semi Colon) Class RunTimeTimeError1
} {
} public static void main(String args[])
{
▪ When executing this program produces int a= 10;
the following error message: int b = 5;
int c = 5;
CompileTimeError1.java :6: ‘;’ expected int x = a/(b-c); //division by zero error
System.out.println(“ Hello Java!”) System.out.println(“x =”+x);
^ int y = a/(b+c);
1 Error. System.out.println(“y =”+y);
Most of the compile-time errors are due to }
typing mistakes. }
It displays the following message and stops
The most common compile-time errors are:
execution
▪ Missing semicolons
Java.lang.ArithmeticException: / by zero
▪ Missing brackets in classes and
Exceptions:
methods
Exception: An Exception is a condition caused
▪ Misspelling of identifiers and keywords
by a runtime error in a program. It is an
▪ Missing double quotes in strings
abnormal event that arises during the execution
▪ Use of undeclared variables
of the program and terminates the normal flow
▪ Use of Incompatible types in
of the program. Java has a built-in mechanism
assignments / initialization
for handling runtime errors, known as
▪ Bad references to objects
exception handling.
▪ Use of = in place of = = operator
Exception Handling: Handling runtime errors
Run-Time Errors:
is known as exception handling. When an
Sometimes, a program may compile
abnormal condition occurs within a method
successfully and it also creates a .class file but
then JAVA throws an exception in the form of
it may not run properly.
Exception Object. If the exception object is not
▪ It may produce wrong result due to
caught and handled properly, the interpreter
wrong logic or may terminate due to
will display an error message and it will
errors such as ‘divide by zero’.
terminate the program. If we want the program
to continue with the execution of the remaining
Most common run-time errors are:
code, then we should try to catch the exception.
Advantages of Exception-handling in Java:
▪ Dividing an integer by zero
▪ It ensures safer termination of a
▪ Accessing an element that is out of the
program.
bounds of an array
▪ It demands proper input entry or proper
▪ Trying to store an incompatible value
handling of a program.
into an array
▪ User has a chance to correct the
▪ Passing an invalid parameter for a
accidental mistakes while running a
method
program.
▪ Trying to illegally change the state of a
thread
Exception Handling
Exception Handling: Handling runtime errors is
known as exception handling.
When an abnormal condition occurs within a
method then
• JAVA throws an exception in the form
of Exception Object.
• If the exception object is not caught and
handled properly, the interpreter will
display an error message and it will
terminate the program.
• If we want the program to continue with
the execution of the remaining code,
then we should try to catch the
exception. It has the following syntax:
The purpose of exception handling is to detect try
and report an "exceptional condition", So that {
appropriate action can be taken. Statements that may cause an exception
The mechanism performs the following tasks: }
1. Find the problem. catch(Exception-Type1 a)
2. Inform that an error has occurred (Throw {
the exception) Statements to handle exception ‘a’
3. Receive the error information (Catch the }
exception) catch(Exception-Type2 b)
4. Take corrective actions (Handle the {
exception) Statements to handle exception ‘b’
The error handling code basically consists of }
two segments: ….
• one to detect errors and to throw ….
exceptions and finally
• The other to catch exceptions and to {
take appropriate actions. Statements;
}
Exception handling mechanism includes the
key words: try, catch, throw, throws and try-block: “try” block contains the code that
finally. may cause a runtime error. It throws
Exception object. A try block must be followed
The following figure shows the exception by at least one catch block or a finally block.
Handling mechanism:
catch-block: “catch” block contains the code
to handle runtime errors i.e. when run time
error occurs then, the control comes to “catch”
block.
• We can write multiple “catch” blocks to
handle different errors. We must
mention the type of exception in a
“catch” block.
finally block
Multiple catch blocks
Several types of exceptions may arise when The finally block is always executed, regardless
executing the program. They can be handled by of whether or not an exception is thrown.
using multiple catch blocks for the same try
block. It is recommended for actions like closing file
In such cases, when an exception occurs the run streams and releasing system resources.
time system will try to find match for the • If no exception occurs during the
exception. When a match is found then the running of the try-block, all the catch-
corresponding catch block will be executed. blocks are skipped, and finally-block
class Test will be executed after the try-block.
{
public static void main(String args[]) • The finally block may be added after the
{ catch block, or after the last catch block.
try
{
int x=Integer.parseInt(args[0]); finally block after the catch block:
int y=Integer.parseInt(args[1]); try
System.out.print("Division="+ (x/y)); {
} Statements that may generate
catch(ArithmeticException ae) the exception
{ }
System.out.println("Denominator was finally
zero"); {
} Statements to be executed before
catch(NumberFormatException ne) exiting exception handler
{ }
System.out.println("Please supply Here, it moves to finally block but does not
numbers"); handle the exception.
}
catch(ArrayIndexOutOfBoundsException ie) finally block after the last catch block:
{ try
System.out.println("Please supply two {
arguments "); Statements that generate the exception
} }
} catch(Exception-Type1 a)
} {
Statements to process the exception ‘a’
The above program produces the following }
output in different runs. …. // other catch blocks
c:\jdk1.5\bin>java Test 8 0 ….
Denominator was zero finally
c:\jdk1.5\bin>java Test xx yy {
Please supply numbers Statements to be executed before exiting
c:\jdk1.5\bin>java Test 5 exception handler
Please supply two arguments }
Applet Programming
know the applet's URL. It must be specified in Building Applet Code/Procedure to create
the CODEBASE attribute of HTML. and execute an applet
The following are the steps to create and
execute an applet:
1. Building an applet code (.Java file) by
importing Applet class.
2. Creating an executable applet (.class file)
3. Designing a Web page using HTML tags
4. Preparing the <applet> tag
5. Adding <applet> tag to the html document.
6. Running the applet.
Example: Output:
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to
Applets”,10,50); Applet tag
} Applets are embedded in HTML documents
} with the <APPLET> tag. The Applet tag
Step 4: Compiling the Program: provides the name of the applet to be loaded and
• After writing the program, we can also tells the browser how much space it
compile it using the command "javac requires. The <applet....> tag included in the
MyApplet.java". body section of HTML file.
• This command will compile our code It has the following syntax:
and can create MyApplet.class file. <APPLET [codebase=codebaseURL]
Step 5: Adding applet to HTML document: code=”Applet file”
• To run the applet we need to create the [ALT=”alternative text]
HTML document. [name=AppletInstanceName]
• The BODY section of the HTML Width=pixels height= pixels
document allows APPLET tag. [align= alignment]
>
MyApplet.html: [<param name=”Attributename” value
=”Attribute value”]
<html> [<param name=”Attributename” value
<body> =”Attribute value”]
<applet code ="MyApplet.class" width=800 ........
height=500> [HTML displayed in the absence of java]
</applet> </APPLET>
</body>
</html> CODEBASE: (codebaseURL): This attribute
specifies the URL of the applet.
Step 6: Running an applet: CODE: (appletFile): This attribute gives the
An applet can be run in two ways name of the file that contains the applet's class
file.
1. Using appletviewer: To run the ALT: (alternateText): This attribute specifies
appletviewer, type appletviewer any text that should be displayed if the browser
filename.html can't run Java applets.
NAME: (appletInstanceName): This attribute
2. Using web browser: Open the web specifies a name for the applet instance, which
browser, type in the full address of makes it possible for applets on the same page
html file. to find and communicate with each other.
WIDTH, HEIGHT (in pixels): These
attributes give the initial width and height (in
pixels) of the applet display area.
ALIGN (alignment): This attribute specifies
the alignment of the applet. The possible values