Java Notes (IV Unit) Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Chaitanya Degree College B.Sc.

V Sem (Java Notes)

Unit IV
Multithreaded Programming
The ability of Operating System to execute several programs simultaneously is known as
“multitasking”, in system technology it is called “Multithreading”. Here the program or process is
divided into two or more subprograms or processes, which can be executed at the same time in
parallel. This is nothing but dividing the task into subtasks executing these subtasks independently
and simultaneously.
A normal system consists only one processor so it executes one task at a time. While
performing multiple tasks it switches among the process so fast that it appears like all of them
executing simultaneously. All java programs which we executed so far now have only a single
sequential flow of control, so at any time only one statement under execution.
Thrread: A thread is like a program, it has a start, a body and an end, executes command
sequentially, so all our earlier java programs are “single-threaded” programs. Each program must
contain at least one thread.

Multithreaded program: Java supports multithreading. There may be multiple flows in a java
program, which act as separate tiny programs called threads executes simultaneously and
independently. Such programs are
called “Multi-threaded programs”. The
_________
ability of a language to support _________
multithreads is called “concurrency”. _________
The figure explains the process _________
multithreading _________
Here the program consist four _________
threads, one main thread and three _________
Main Thread
other threads. The main thread is main __
method module that creates and starts
other threads.
After initiated by main thread
the threads A,B, C run concurrently _________ _________ _________
and share all resources jointly. They _________ _________ _________
execute in parallel but really the flow of _________ _________ _________
execution is shared among threads, _________ _________ _________
the interpreter switches the control _________ _________ _________
among the threads so that it appears _________ _________ _________
they are running concurrently. _________ _________ _________
Thread A Thread B Thread C
__ __ __
Differences between multithreading and multitasking:
multithreading multitasking
It is a programming concept It is a Operation system concept
It is used to develop efficient programs It is used to develop efficient Operating Systems
It is High efficient It is less efficient compare to multithreading
The processor switches among threads The processor switches among programs
It executes multiple parts of a single program It executes multiple programs simultaneously
simultaneously
A thread is the smallest unit A program is the smallest unit
Creating Threads: Threads are implemented using objects that contain the method called run(). The
run method is the soul and heart of thread. It is the only one method of thread in which we place the
statements for implementing thread. The run is defined as public void run(). The run method is
invoked by an object of concerned thread using another thread method called start().
There are two methods to create threads: they are
1. By creating a thread class
2. By converting a class to thread
1. By creating a thread class: We create a thread by extending the class java.lang.Thread. Now
we can access all the thread methods directly using the following steps:

Unit IV 1
Chaitanya Degree College B.Sc.V Sem (Java Notes)
Class <class name> extends Thread
{
public void run()
{
::::::::::::::::::::::::::::
::::::::::::::::::::::::::::
}
}
After creating the thread we may start a thread using below statements.
<Thread class name> < Object name> = new <Thread class name>();
<Object name>.start();
The first statement creates a new object, now the thread is in a newborn state.
The second statement moves the thread into the runnable state. It invokes run method now the
thread is in the running state.
Ex: program for creating and running a thread class
class a extends Thread }
{ class c extends Thread
public void run() {
{ public void run()
for(int i=1;i<=5;i++) {
{ for(int k=1;k<=5;k++)
System.out.println("Thread a, i = "+i); {
} System.out.println("Thread c, k = "+k);
System.out.println("Exit form a"); }
} System.out.println("Exit form c");
} }
class b extends Thread }
{ class threadtest
public void run() {
{ public static void main(String args[])
for(int j=1;j<=5;j++) {
{ new a( ).start( );
System.out.println("Thread b, j = "+j); new b( ).start( );
} new c( ).start( );
System.out.println("Exit form b"); }
} }
Life Cycle of a Thread: During the life cycle of a thread it has many states they are;
1. Newborn state 2. Runnable state 3. Running state 4. Dead state.
1. Newborn state: When we create a new thread object, it is said to be newborn state. At this stage
we done only two things with the Thread, move to runnable state using starat() method or kill it using
stop() method.
2. Runnable state: In this state the thread is ready for execution, and waiting for the availability of
the processor. It joins with the queue of other threads that have same priority; they are given time
slots for execution, and executed in the fashion first-come, first-serve manner. This is known as
time-slicing. We may relinquish control to another thread of equal priority before its turn comes
using the method yield().
3. Running state: When the processor gives its time to the thread for its execution, it is called
running state. It runs until it relinquishes or it is preempted by a higher priority thread. A running
thread may relinquish by various methods;
i. suspend and resume: suspend() method is used to suspend the thread for some time
but does not kill. The suspended thread is revived using resume() method.
ii. sleep: sleep(time) method is used to suspend the thread for specified time period. After
the specified time period it re-enters the runnable state, here the time is in milliseconds.
iii. wait and notify: wait() method is used to wait the thread until a specified event occurs. It
is scheduled to run again using the notify() method.

Unit IV 2
Chaitanya Degree College B.Sc.V Sem (Java Notes)
4. Blocked State: When a thread is prevented form entering the runnable state to the running state,
it is said to be in Blocked state. It happens when we use suspend, sleep or wait methods. This is
also called not runnable state, it is not a dead state, it is fully qualified to run again.
5. Dead State: A running thread ends its life when it has completed executing its run() method. This
is a natural death. But using stop() method we may kill the thread in the middle, it is called premature
death. It is called dead state. A thread is killed as soon as it is born, while running, or even at
blocked state.
Newborn State

Runnable Running stop Dead


yield
State State State

suspend, sleep, wait Resume, notify

Blocked State

Life Cycle and State transition diagram of a Thread


WAP to Demonstrate Thread methods.

class a extends Thread System.out.println("Thread c, k = "+k);


{ if(k==1)
public void run() try
{ {
for(int i=1;i<=5;i++) sleep(1000);
{ }
if(i==1) yield(); catch(Exception e) { };
System.out.println("Thread a, i = "+i); {
} }
System.out.println("Exit form a"); }
} System.out.println("exit form c");
} }
class b extends Thread }
{ class threadtest1
public void run() {
{ public static void main(String args[])
for(int j=1;j<=5;j++) {
{ a at = new a();
System.out.println("Thread b, j = "+j); b bt = new b();
if(j==3) stop(); c ct = new c();
} System.out.println("Start thread a");
System.out.println("Exit form b"); at.start();
} System.out.println("Start thread b");
} bt.start();
class c extends Thread System.out.println("Start thread c");
{ ct.start();
public void run() System.out.println("End of main Thread");
{ }
for(int k=1;k<=5;k++) }
{
Thread Priority: Threads in java are associated with priority, which affects the order in which they
execute. When all the threads are equal priority they are given equal priority so they share the
processor on a first-come, first-serve basis. When we set different priorities to threads, which are
ready to execute they java system chooses the highest priority thread and executes it. So java
executes the threads from higher priority to lower priority. Priority is set using setPriority method.
Unit IV 3
Chaitanya Degree College B.Sc.V Sem (Java Notes)
ThreadName.setPriority(intNumber);
The intNumber is any value between 1 and 10.
Ex: Program to demonstrate Thread priority.
class a extends Thread System.out.println("Thread c started");
{ for(int k=1;k<=5;k++)
public void run() {
{ System.out.println("Thread c, k = "+k);
System.out.println("Thread a started"); }
for(int i=1;i<=5;i++) System.out.println("Exit form c");
{ }
System.out.println("Thread a, i = "+i); }
} class threadpriority
System.out.println("Exit form a"); {
} public static void main(String args[ ])
} {
class b extends Thread a ta = new a( );
{ b tb = new b( );
public void run() c tc = new c( );
{ tc.setPriority(10);
System.out.println("Thread b started"); tb.setPriority(5);
for(int j=1;j<=5;j++) ta.setPriority(1);
{ System.out.println("Starting of Thread a ");
System.out.println("Thread b, j = "+j); ta.start();
} System.out.println("Starting of Thread b ");
System.out.println("Exit form b"); tb.start();
} System.out.println("Starting of Thread c ");
} tc.start();
class c extends Thread System.out.println("End of main Thread");
{ }
public void run() }
{
2. Creating Thread using “Runnable” interface: We may create threads in java using “Runnable”
interface to implement threads. It declares run method to implement Thread; steps for this is:
1. Declare a class as implementing the Runnable interface.
2. Implement the run() method in that class.
3. Create a thread by defining an object as “runnable” class as the target of thread.
4. Use start method to run the thread.
Ex program to use Runnable interface.
class cdc implements Runnable class runinterface
{ {
public void run() public static void main(String args[ ])
{ {
for(int i=1;i<=10;i++) cdc runnable = new cdc();
{ Thread t = new Thread( runnable);
System.out.println("Thread cdc : "+i); t.start();
} System.out.println("End of main thread");
System.out.println("End of Thread cdc"); }
} }
}
Synchronization: a Thread uses own data and methods inside its run() method. It can also use data
and methods outside the thread, in such occasions; they may compete for the same resource with
other thread. Suppose two threads trying to read and update data of a single file, gets strange results.
To overcome such problems we use the technique “synchronization” using keyword “synchronized”.
When we declare a block or method synchronized, java creates a “monitor” and hands it to the thread
that calls the method first time. As long as the thread holds the monitor no other thread can enter the
synchronized block or method. After the thread has completed its work then the method or block is
handed over to the next thread that is ready to use the same resource.
Ex: synchronized void update()
Unit IV 4
Chaitanya Degree College B.Sc.V Sem (Java Notes)
Thread Exceptions: When we work with thread methods mainly sleep(), we have to put it in the try
block caught by catch block. This is necessary other wise it will not compile. Java provides many
methods to catch exceptions related to Threads they are:
1. IllegalThreadStateException: used when we attempt to invoke a method that a thread
cannot handle I the given state.
2. InterrptedException: used to handle exception that it cannot handle it in the current state.
3. IllegalArgumentException: used to handle illegal method argument
4. Exception e: used to handle any other exception.

Applet Programming
An applet is a Java program used in Internet Computing. They can be transported from one
system to another over internet. An applet is executed using “appletviewer” or any web browser.
Applets are used to perform tasks like normal programs and used to display graphics, animation etc.,
Local and Remote Applets: Applets are two types
Local Applets: An applet developed and stored in local system is called “local Applet”. For this
there is no need of internet connection.
Remote Applets: An applet which is developed by someone else and stored on a remote computer
connected to the internet is known as “remote applet”. We can down load a remote applet to our
local computer through internet.
Differences between applets and application programs:
1. Applets are not full-featured application programs.
2. Applets do not use main() method for initiating.
3. Applets cannot run independently, they are executed using a special feature known as HTML
tag.
4. Applets cannot read/write data into files.
5. Applets cannot communicate with other servers on the network.
Preparing to write Applets: There are few steps in preparing an applet: they are:
1. Building an applet code using any text editor and saving as .java file.
2. Compiling the above code to create an executable applet .class file.
3. Designing a web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APLET> tag into the Web page.
6. Creating HTML file.
7. Testing the applet code.
Building Applet Code: An applet program uses two classes Applet and Graphics. The Applet
class is located in the package java.applet, Graphics class is located in java.awt package. A stand
alone program calls main method to initiate the execution where as an Applet program uses paint
method to display the output when it is called. The out put may be text, graphics or sound. The paint
method requires a Graphics object as argument like below
Public void paint(Graphics g)
The general form of an Applet program is:
import java.awt.*;
import java.applet.*;
public class <applet class name> extends Applet
{
::::::::::::::::::::::::::::::
Public void paint(Graphics g)
{
:::::::::::::::::::::::::::::
}
::::::::::::::::::::::::::::
}
The code must be saved as <applet classnname>.java

Unit IV 5
Chaitanya Degree College B.Sc.V Sem (Java Notes)
Creating an Executable Applet: This is nothing but creating .class file, by compiling the source file
of applet, for this type “javac <applet file name>.java” at command line. Then it creates a class file
with same name and saves in the same directory.
Applet Tag: Applet tag is essential to view the applet program Applet is one of the Tags of Web
Page. To display the output we have to use applet tag as below, so type the code in notepad
<APPLET
CODE = <applet file name>.class
width = 500
heitht = 600 >
</APPLET>
Save the above code as <applet filename>.html in the same directory.
This is HTML Code, it tells the browser to compile the given class file, which is in the same directory.
The width and height are the area of the applet in pixels.
Running the applet: We may run applet in two methods they are
1. using java-enabled browser (like HotJava or NetScape)
2. using appletviewer.
When we use a browser it displays the entire website containing the applet. When we use
appletviewer it will display only the output of the applet. The appletviewer is a part of Java
Development Kit, so we may easily use this. For this we require three files loaded in the same
directory they are .java, .class and .html files
Type “appletviewer <applet file name>.html at command line to view the applet output.
Applet Life Cycle: An applet has many stages in its life cycle they are:
1. Initialization State: When any applet is loaded it enters its initialization state by calling the
method init() of Applet class. At this state we may create objects, setup initial values, load
images or fonts and setup colors. This stage occurs only once in the life cycle of applet.
2. Running State: An applet enters the running stage when the start() method of the Applet
class is called. This occurs automatically after it is initialized. We may use start() method to re
start the stopped Applet. It may occur many times.
3. Idle or Stopped state: An applet moves the Idle or stopped state when it is stopped
from running. It is automatically occur when we leave the page containing the currently
running applet.
4. Dead State: An applet is said to be dead when it is totally removed form memory. It occurs
by invoking the destroy() method. It happens only once in the life cycle of the applet.
5. Display State: Applet moves to display state when it has to perform some output operations
on the screen. It happens immediately after it enters the running state. The paint() method is
called to perform the task.

Initialization

start()

Running stop() destroy()


Idle or
Display Dead
Stopped
Paint() start()

Life cycle and transition diagram of an Applet

Designing a web page: A Web page is essential to run a java applet program; it is basically a text
file with HTML tags. These files are interpreted by a web browser or applet viewer. These are called
HTML files or HTML documents stored with an extension of .html. This file must be stored in the
same folder in which the applet file is saved. This is started with a opening tag <HTML> and ends
with a closing tag </HTML>. It contains three major sections.

Unit IV 6
Chaitanya Degree College B.Sc.V Sem (Java Notes)
1. Comment section: This section contains comments about web page. This is an option
comments are added at any stage in the file, they are included between <! And >.
2. Head Section: This section begins with a tag <HEAD> and ends with </HEAD>. This is also
optional. It contains the title of the page, used to display in the title bar. We should place the
title between the tags <TITLE> and </TITLE>.
3. Body section: it comes after head section. It contains the entire information of the web
page. This stage starts with tag <BODY> and ends with </BODY>. It contains tags like
<CENTER> and </CENTER> used to center the given text, <H1> and </H1> to </H6> and
<H6> to display text in various sizes.
The body section contains a tag called APPLET used to load Applet program. To display an
applet the web page must contain at least applet tag, starts with <APPLET> and ends with
</APPLET>.

Managing Errors and Exceptions


Errors are most commonly occurred while working with programs. They produce unexpected
results. Errors are mainly two types they are:
1. Compile-Time Errors: All the errors detected by java compiler are called compile time errors,
when a program has such errors the compiler does not create .class file. While compiling it displays
the error messages. We have to correct these errors to recompile the file. These include missing
semicolons, type mismatch, missing brackets and braces misspelling of keywords etc.,
2. Run Time Errors: These errors occur during the run time(while executing). Some times class file
is created successfully, but while running some errors will be occurred then it displays a message and
stops the program execution. The most commonly occurred run time errors are:
• Dividing a number by zero
• Accessing an element that is out of the bonds of array
• Trying to cost on instance of a class to one of its subclasses
• Attempting to use a negative size of array
• Converting invalid string to number
• Passing a parameter that is not in a valid range or value for method
Exceptions: An exception is a condition that is caused by a run-time error. When it faces such
errors, it creates exception object and throws it. If we fail to catch the exception it will display an error
message and will terminate the program. If we want to run the code we have to catch the exception
object and we have to take corrective actions. This is called “exception handling”. It consists
following tasks:
1. Finding the problem or error(Hitting the exception)
2. Informing about the error(Throwing exception)
3. Receiving the error information(Catching the exception)
4. Taking corrective actions(Handling exception)
Some common exceptions:
1. ArithmeticException 7. SecurityException
2. ArrayIndexOutOfBoundsException 8. StackOverFlowException
3. ArrayStoreException 9. StringIndexOutOfBoundsExcepion
4. FileNotFoundException 10. IOException
5. NullPointerExcepion 11. NumberFormatException
6. OutOfMemoryExcepion
Exceptions are classified into to types in java:
1. Checked exceptions: These are handled in the code with the help of try and catch blocks.
These are extended form java.lang.Excepion class.
2. Unchecked exceptions: These exceptions are handled by JVM, these are extended form
java.lang.RuntimeExcepion class.
Syntax of Exception handling code: Java provides a key word try to through the exception, so we
have to place the code in try block in which we are excepting error. The try block must followed by
catch block to catch the exception. We may use two or more catch blocks also,

Unit IV 7
Chaitanya Degree College B.Sc.V Sem (Java Notes)

Nested try statements:


try
{
Statements:
Syntax: try
::::::::::::::::::::::::: {
Try statements;
{ }
Statements; (The code in which we are excepting error) catch(Excepion e)
} {
catch(Excepion e) statements:
}
{
}
Statements: (The code to handle Error) Catch(Excepion e)
} {
::::::::::::::::::::::: Statements
}

Multiple catch statements and finally statement: it is possible to use multiple catch statements
with one try block as below. Java provides another statement called finally that is used immediately
after try block or after last catch block. It is used to handle any type of exception that is not caught by
any of the previous catch statements.
:::::::::::::::::::::::::
Try
{
Statements;
}
catch(Excepion Type-1 e)
{
Statements:
}
catch(Excepion Type-2 e)
{
Statements:
}
:::::::::::::
catch(Excepion Type-3 n)
{
Statements:
}
finally
{
Statements;
}
Throwing our own exceptions: We may also throw our own exceptions, using the keyword throw.
Syntax: throw new <Throwable subclass name>
Here throwable subclass is a user defined class and it is the sub class of Exception class of java.lang
package.

THE END

Unit IV 8

You might also like