Professional Documents
Culture Documents
JAVA2
JAVA2
Multithreaded programming
Introduction:-
Modern operating systems such as Windows 95 and windows XP may
recognize that they can execute several programs simultaneously.
This ability is known as multitasking. In system’s terminology, it is called
multithreading.
It is a conceptual programming paradigm where a program is divided into two
or more subprograms, which can be implemented at the same time in parallel.
1 Dept Of CSE
MIST,Sathupally JAVA
For example
class bsc extends Thread
{
……………..
Body of the class;
…………….
}
Implementing the run( ) method:-
}
Starting new thread:-
To actually create and run an instance of our thread class, we must write the following
Classname threadname =new classname( );
Threadname.start( );
2 Dept Of CSE
MIST,Sathupally JAVA
for(int i=0;i<4;i++)
{
System.out.println("thread A"+i);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=0;j<4;j++)
{
System.out.println("Thread B"+j);
}
}
}
Out put
class c extends Thread Thread B 0
{ Thread A 0
public static void main(String args[]) Thread B 1
{ Thread A1
B obj=new B(); Thread B 2
A o=new A(); Thread A 2
obj.start(); Thread B 3
o.start(); Thread A 3
}
}
Syntax:- Threadname.stop( );
For example
Athread.stop( );
In the above example statement causes the thread to move to the dead state.
A thread will also move to the dead state automatically when it reaches the end of its
method.
The stop( ) method may be used when the premature death of a thread is desired.
Blocking a thread:-
A thread can also be temporarily or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods.
3 Dept Of CSE
MIST,Sathupally JAVA
A o=new A();
obj.start();
o.start();
}
}
Q) Explain the lifecycle of a thread?
(or)
Explain the state transition diagram of a thread?
Life cycle of a thread:-
During the life cycle of a thread, there are many states it can enter.
The following are the states of a thread.
1. New born state 2. Runnable state 3. Running state 4. Blocked state
5.Deadstate.
A thread is always in one of these five states.
It can move from one state to another via a variety of ways.
New born
start stop
stop
Dead
Runnin Runnable
g
Yield
suspend resume
sleep notify stop
Ideal state
(not – runnable) Blocked
Fig: State transition diagram of a thread
Newbor
n
state
5 Dept Of CSE
MIST,Sathupally JAVA
Runnabl Dead
e state
state
Fig:- scheduling a new born thread
Runnable state:-
The runnable state means that the thread is ready for execution and is waiting
for the availability of the processor.
That is the thread has joined the queue of threads that are waiting for
execution.
If all threads have equal priority , then they are given time slots for execution
in round robin fashion.
Round robin means first – come , first – serve manner. This process of
assigning time to threads is known as time – slicing.
If we want a thread to control another thread to equal priority, we can use the
yield( ) method.
Running state:-
Running means that the processor has given its time to the thread for its
execution.
A running thread may be control in one of the following situations.
It has been suspended using suspend( ) method , a suspend thread can be
retrieved by using the resume( ) method. This approach is useful when we
want to suspend a thread for some time.
6 Dept Of CSE
MIST,Sathupally JAVA
It has been made to sleep. We can put a thread to sleep for a specified time using the
method sleep(time) , where time is in milliseconds. This means that the thread is out
of the execution for a specified time period.
It has been told to wait until some event is occurs. This is done using the wait( )
method. The thread can be run again using the notify( ) 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.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy
certain requirements.
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 complete the execution of its run( )
method. It is a natural death.
7 Dept Of CSE
MIST,Sathupally JAVA
However, we can kill it by sending the stop message to it at any state thus
cause the premature death to it.
A thread can be killed as soon it is born, or while it is running, or
runnable(blocked) states.
Syntax:- Threadname.setpriority(intnumber);
In the above example intnumber 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 intnumber may assume one of these constants or any value between 1 and 10.
The default setting is NORM – PRIORITY.
For example, we may need to answer as quickly as possible. Whenever multiple
threads are ready for executions, the java system choose the highest priority thread
and executed it.
For a thread of lower priority wait until the following things are happen.
It stops running at the end of run( )
It is made to sleep using the sleep( )
It is told to wait using the wait( )
Remember that the highest priority thread is always process(executes) first to any
lower priority thread.
Q) Write a program for using the concept of thread priority
import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=0;i<4;i++)
{
System.out.println("thread A"+i);
}
8 Dept Of CSE
MIST,Sathupally JAVA
}
}
class B extends Thread
{
public void run()
{
for(int j=0;j<4;j++)
{
System.out.println("Thread B"+j);
}
}
}
Out put
class C extends Thread Thread C 0
{ Thread B 0
public void run() Thread A 0
{ Thread C 1
for(int k=0;k<4;k++) Thread B 1
{ Thread A1
System.out.println("Thread C"+k); Thread C 2
} Thread B 2
} Thread A 2
} Thread C 3
class D extends Thread Thread B 3
Thread A 3
{
public static void main(String args[])
{
B obj=new B();
A o=new A();
C rr =new C();
rr.setPriority( 10);
obj.start();
o.start();
rr.start();
}
}
9 Dept Of CSE
MIST,Sathupally JAVA
An error may produce an incorrect result (output) or terminate the execution of the
program.
Therefore important to detect and manage properly all the possible errors.
Q) Explain the types of errors?
Types of errors:- Errors are classified into two types. Those are
Compile – time errors
Run – time errors.
Compile – time errors:-
All syntax errors will be detected and displayed by the java compiler and
therefore these errors are known as compile – time errors.
It is also called as syntax errors.
Whenever the compiler displays an error, it will not create the .class file.
The following example program displays the compile time error.
1 error
We can now go to the appropriate line ,correct the error, and recompile the program.
Sometimes a single error may be the source of multiple errors.
Most of the compile – time errors are due to the typing mistakes.
The most common problems are
Missing the semicolons
Missing double quotes in strings
Misspellings of identifiers and keywords
Use of undeclared variables
Bad references to objects
And so on
10 Dept Of CSE
MIST,Sathupally JAVA
Java.lang.arithmeticException : by zero
At error . main(error.java10)
11 Dept Of CSE
MIST,Sathupally JAVA
appropriate message for taking the corrective action. This is known as exception
handling.
The purpose of exception handling mechanism is to detect and report
errors, so that appropriate action can be taken.
The mechanism of error handling code performs the following tasks.
Find the problem (Hit the exception).
Inform that an error has occurred (Throw the exception)
Receive the error information (Catch the exception)
Take corrective action (Handle the exception)
The error handling code basically consists of two segments, one is to detect
errors and other to catch the exception.
Some of the common exceptions are listed bellow
Out of memory exception Caused when there’s not enough space to allocate
A new object
The basic form of exception handling are throwing an exception and catching
it.
The general form of exception handling is
Try Block
Syntax:- Exception object creator
Statements that
cause an exception
Throws exception
Object
Catch Block
Statements that
handle the
12 Dept Of CSE
exception
MIST,Sathupally JAVA
Exception handler
try
{
Syntax:-
Statements; /** generates exception */
}
catch(Exception – type e)
{
Statements; /** process the exception */
}
The try block can have one or more statements that could generate an exception.
If any one statement generate an exception and the remaining statements are skipped
and execution jumps to the catch block.
The catch block too can have one or more statements that are necessary to process the
execution.
Every try statements should be followed by at least one catch statement.
Note:- The catch statement works like a method definition.
The catch statement is reference to the exception object. If the catch parameter
matches with the type of exception object then the catch block statements are
executed.
The following example illustrate the exception handling
Write a program for using the concept of exception handling mechanism
class ss
{
public static void main(String ss[])
{
int a=100,b=50,c=50;
int x,y;
try
{
x=a/(b-c);
System.out.println("x value is"+x);
}
13 Dept Of CSE
MIST,Sathupally JAVA
catch(ArithmeticException e)
{
System.out.println("division by zero");
Output of the above program
}
y=a/(b+c); Division by zero
System.out.println("y value is"+y); Y value is 1
}
}
Note:- In the exception handling mechanism program did not stop at the point of error
condition. It catches the error condition, prints the error message, and then continues
the execution of the remaining program.
try
{
Syntax:- Statements; /** generates exception */
}
catch(Exception – type - 1 e)
{
Statements; /** process the exception 1 */
}
catch(Exception – type - 2 e)
{
Statements; /** process the exception 2 */
}
……….
……….
catch(Exception – type - n e)
{
Statements; /** process the exception -n */
}
Java treats the multiple catch statements like in switch statements.
Exception is generated by try block, if any one catch statements matches with
the exception object then that catch statement will be executed and the
remaining catch statements will skipped.
Write a program for using the concept of exception handling mechanism with multiple
catch statements
class ss
{
public static void main(String ss[])
14 Dept Of CSE
MIST,Sathupally JAVA
{
int a=100,b=50,c=50;
int x,y;
try
{
x=a/(b-c);
System.out.println("x value is"+x);
}
catch(ArithmeticException e)
Output of the above program
{
System.out.println("division by zero"); Division by zero
} Y value is 1
catch(ArrayStoreException e)
{
System.out.println(" Array error ");
}
y=a/(b+c);
System.out.println("y value is"+y);
}
}
Finally statement:-
Java supports another statement known as finally statement that can be used to handle
an exception.
If use the catch blocks and finally block in the same program, if any of the catch
block can not catch the exception, then the finally block is executed.
Finally block can be used to handle any exception generated with a try
block.
It may be added immediately after the try block or last catch block.
The general form of finally block is as follows.
try
{
Statements; /** generates exception */
Syntax:- }
catch(Exception – type - 1 e)
{
try Statements; /** process the exception 1 */
{ }
Statements; /** generates exception */ catch(Exception – type - 2 e)
} {
(or)
finally Statements; /** process the exception 1 */
{ }
Stayements; /** process the exception */ ………..
} ………….
finally
{
15 Dept
Statements; /** Ofthe
process CSEexception 2 */
}
MIST,Sathupally JAVA
When a finally block is defined, then that finally block is automatically execute either
exception is created or not.
Write a program for using the concept of exception handling mechanism with finally
statements
class ss
{
public static void main(String ss[])
{
int a=100,b=55,c=5;
int x,y;
try
{
x=a/(b-c);
System.out.println("x value is"+x);
}
catch(ArithmeticException e)
Output of the above program
{ X value is 2
System.out.println("division by zero"); Division by zero in finally block
} Y value is 1
finally
{
System.out.println("division by zero in finally block ");
}
y=a/(b+c);
System.out.println("y value is"+y);
}
}
16 Dept Of CSE
MIST,Sathupally JAVA
Applet Programming
Introduction:-
Applets are small java programs that are primarily used in internet
programming.
They can be transported over the internet from one computer to another and
run using the applet viewer or web browser that supports java.
It can perform the arithmetic operations, display the graphics, play sounds,
create animations and play the internet games.
Internet users retrieve and use the programs on the world wide network.
Java has enabled them to create and use fully interactive multimedia.
Applet:-
Applets are small java programs that are primarily used in internet
programming.
17 Dept Of CSE
MIST,Sathupally JAVA
They can be transported over the internet from one computer to another and
run using the applet viewer or web browser that supports java.
Applets are classified into two types
1. Local Applet
2. Remote Applet
Local applet:-
An applet developed locally and stored in local system is known as a local applet.
It does not need to use the internet connection.
It simply searches the directories in the local system and loads the specified applet.
Remote applet:-
A remote applet is that which is developed by someone else and stored on a
remote computer connected to the internet.
If our system is connected to internet, we can download the remote applet onto
our system and run it.
Q) Explain the difference between applet and applications?
Difference between applet and applications:-
Both applets and applications are java programs. They are significant difference
between them.
Applets are not full – featured application programs. They are usually designed for
use on the internet.
The main difference between applets and stand –alone applications is as follows.
Applet do not use the main( ) method for initiating the execution of the code.
Applets can not be run independently. They are run from inside a webpage
using a special feature known as HTML Tags.
Applets cannot communicate with other servers on the network.
Applets do not use the native methods (C or C++ style functions) but
applications use the native methods.
Preparing to Write an applet:-
We have to create simple java application program with a single main
method that creates the objects.
We will be creating applets exclusively and therefore we will need to know
When to use applets
How an applet works
What are features of an applet
Where to start and when we first create our own applets.
Q) Explain the lifecycle of an applet?
Applet lifecycle:-
During the life cycle of an applet, there are many states it can enter.
The following are the states of an applet.
1. Born (or) Initialized state
2. Running state
3. Idle state
4. Dead (or) Destroyed state.
18 Dept Of CSE
MIST,Sathupally JAVA
Begin Bor
(load applet) n
start( )
stop( )
Run
Display ning Idle
paint( ) start( )
destroy( )
destroyed End
Dea
d
Fig: State transition diagram of an Applet
Running state:-
Applets enter the running state when the system calls the start( ) method. This
occurs automatically after the applet is initialized.
19 Dept Of CSE
MIST,Sathupally JAVA
Applet starting can also occurs if the applet is already in “stopped” state or Idle
state.
The stat( ) method to create a thread to control the applet.
The general form of start( ) method is
Dead state:-
An applet is said to be dead when it is removed from the memory.
This occurs automatically by invoking the destroy( ) method when we quit the
applet.
Destroying state occurs only once in the applet lifecycle.
The general form of destroy( ) method is
20 Dept Of CSE
MIST,Sathupally JAVA
<HEAD>
<TITLE>
Welcome
</TITLE>
</HEAD>
21 Dept Of CSE
MIST,Sathupally JAVA
<HTML>
</
………..
……….. Comment section
>
<HEAD>
Title Tag
</HEAD> Head section
<BODY>
Applet Tag Body section
</BODY>
Body section:-
This section contains entire information about the web page and its behavior.
In this section we can setup many options like as colour, sound, etc….
Consider the following example
<BODY >
<CENTER>
<H1>
WELCOME
</H1>
</CENTER>
</BODY>
The above example <CENTER > Tag show the output( WELCOME) at
screen center.
<H1> Tag show the text to be largest size.
<H2> to <H6> Tags are reduce the letters size in the text.
22 Dept Of CSE
MIST,Sathupally JAVA
APPLET TAG :-
Include the pair of <APPLET> and < /APPLET> Tags in body section.
It supplies the name of the applet and tells the browser how much space to
an applet.
Consider the following example of an applet tag
<APPLET
CODE = Hello.class
WIDTH = 400
HEIGHT = 200>
Tag Function
</ APPLET>
<CENTER > ….. </CENTER> It display the Applet information in middle of the
web page
<APPLET> ……… </APPLET> This tags are used to give the user defined
parameters.
<FONT> … </FONT> Font tag , it is used to change the font colour and
font size
23 Dept Of CSE
</ …….. > Comment tag