Java - UNIT IV
Java - UNIT IV
UNIT – IV
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.
Newborn
New thread
Start
Running Runnable
Active Thread Stop
stopyield Dead Killed thread
New born
start stop
Runnable State Dead state
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
resume
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)
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
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
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)
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
}
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( )
{
-------
}
}
UNIT – V
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:
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
}
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
(i) try
{
…………….
……………
}
finally
{
……………..
……………..
}
(i) try
{
…………
…………
catch(………)
14
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
{
……………
……………
}
catch(……)
{
…………..
…………..
}
.
.
.
.
finally
{
…………..
……….....
}
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
}
}
}
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.
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.
18
III B.Sc CS Java Programming Siri PSG Arts & Science College for
Women
Dead or destroyed state
start ( ) stop( )
Running Idle
Stopped
Destroyed End
Exit of browser
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.
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.
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>
<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>
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.
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
Hello Java
appletloader.started
23