Java Notes (IV Unit) Final
Java Notes (IV Unit) Final
Java Notes (IV Unit) Final
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
Blocked State
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()
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>.
Unit IV 7
Chaitanya Degree College B.Sc.V Sem (Java Notes)
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