0% found this document useful (0 votes)
3 views17 pages

Java III Unit

OUTSIDE THEC LOUD Evaluating webmail services
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Java III Unit

OUTSIDE THEC LOUD Evaluating webmail services
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAMMING IN JAVA

Unit-3 : Interfaces-Packages - Creating Packages - Accessing a Package - Multithreaded programming-


Creating Threads-Stopping and Blocking a Thread-Life Cycle of a Thread-Using Thread Methods-
Thread Priority-Synchronization-Implementing the Runnable Interface.

 Interface:
 An interface is a special case of abstract class, which contains all the abstract methods (methods
without their implementation). An interface specifies what a class must do, but not how to do.

 The interface can be defined just like defining a class with the interface keyword.
 To create an interface, you must write both the interface declaration and the interface body.
 Interfaces are syntactically similar to classes, but they lack instance variable, and their methods are
declared without anybody. Once it is defined, any number of classes can implement an interface. A
class can implements one or more interfaces.

General Form :
[public] interface interface-name
{
Variable Declaration;
Method Declaration;
}
 An interface can extend other interfaces just as a class can extend. However, while a class can only
extend one other class, an interface can extend any number of interfaces.
Syntax:
[public] interface interface-name extends interface 1, interface2,......
{
//final static variables
//public abstract methods
}
Example:
interface one
{
int x=10,y=16;
public void display();
}
interface two extends one
{
public void add();
}
 An interface cannot extend classes.
 An interface inherits all constants and methods from its super interface unless the interface hides a
constant with another of the same name, or re-declares a method with a new method declaration.
 All constant values defined in an interface are implicitly public, static, and final.
 All methods declared in an interface are implicitly public and abstract.
 Implementing interface and Accessing Interface Variables
Implementing interface:
 In order to access the variables and methods of an interface we must implement the interface inside a
class
 All the methods in the interface should be defined in the class that implements the interface.
 A class can implement more than one interface in such case the class should define methods declared
in all the interfaces implemented by that class.
Syntax:
access class class_name [extends superclass ] [implements interface1[,interface 2…]
{
//Variables declaration
//Method definitions
}
When we implement an interface method in a class it should be declared public. The class implementing
an interface can have its own variables and methods. The interface reference variable can only access the
methods of the interface and not of the class.
Example:
/* Program to show a implementing two interfaces */
/* First interface */
interface One
{
int x=12;
}
/* Second interface */
interface Two
{
int y=10;
void display();
}
/* Class implementing the interfaces */
class Demo implements One,Two
{
public void display()
{
[Link]("X in inteface One ="+x);
[Link]("Y in interface Two="+y);
[Link]("X+Y= "+(x+y));
}
}
/* Main class */
class TwoInterface
{
public static void main(String args[])
{
Demo d=new Demo();
[Link]();
}
}

Interface contains final static variables. So the class that implements an interface can use the variables as
constant values within the class but cannot modify it. This is called accessing an interface variable.

Packages
 Java provides a powerful means of grouping related classes and interfaces together in a single unit
called packages. Put simply, packages are groups of related classes and interfaces.
 Packages provide a convenient mechanism for managing a large group of classes and interfaces while
avoiding potential naming conflicts. The Java API itself is implemented as a group of packages.
 Java Packages are classified into two types. The first category is known as Java API packages and the
second is known as user defined package.

The following is the partial graphical representation of the levels of nesting in the java package, its sub-
packages, the classes in those sub-packages, and the subroutines in those classes.

Java API Packages


 The Java API is the set of classes included with the Java Development Environment. These classes are
written using the Java language and run on the JVM. The Java API includes everything from collection
classes to GUI classes.
 Java interfaces and classes are grouped into packages. The following are the java packages, from
which you can access interfaces and classes, and then fields, constructors, and methods.
Java API packages (System package)
java. Lang
Package that contains essential Java classes, including numeric’s, strings, objects, compiler, runtime,
security, and threads. This is the only package that is automatically imported into every Java program.
[Link]
Package that provides classes to manage input and output streams to read data from and write data to
files, strings, and other sources.
[Link]
Package that contains miscellaneous utility classes, including generic data structures, bit sets, time, date,
string manipulation, random number generation, system properties, notification, and enumeration of
data structures.
[Link]
Package that provides classes for network support, including URLs, TCP sockets, UDP sockets, IP
addresses, and a binary-to-text converter.
[Link]
Package that provides an integrated set of classes to manage user interface components such as
windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields. (AWT = Abstract
Window Toolkit)
[Link]
Package that enables the creation of applets through the Applet class. It also provides several interfaces
that connect an applet to its document and to resources for playing audio.
Using System Defined Packages
There are two ways of accessing the classes stored in packages:
 Using fully qualified class name
 Import package and use class name directly.
1. Using fully qualified class Name
Let's say that you want to use the class [Link] .Vector in a program that you are writing. Like any class,
[Link] .Vector is a type, which means that you can use it to declare variables and parameters and to specify
the return type of a function. One way to do this is to use the full name of the class as the name of the type.
For example, suppose that you want to declare a variable named myVector of type [Link] .Vector. You
could write
[Link] myVector = new myVector( );
Once defined we could use myVector object to access the members of Vector class.
2. Import package and use class name directly
Using the full name of every class can get tiresome, so Java makes it possible to avoid using the full name of
a class by importing the class. There are two ways to import a class
a) Importing a particular class in a package
b) Importing all the classes in a package
a) Importing a particular class in a package
Syntax:
import [Link];
If you put
import [Link];
at the beginning of a Java source code file, then, in the rest of the file, you can abbreviate the full name
[Link] to just the simple name of the class, Vector. Using this import directive would allow you to
define
Vector myVector =new myVector();
b) Importing all the classes in a package
A java system package can be accessed either using a fully qualified classname or using import statement. We
generally use import statement.
syntax:
import pack1[.pack2][.pack3].classname;
or
import pack1. [.pack2][.pack3].*;
here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on. In this way we can
have several packages in a package hierarchy. We should specify explicit class name finally. Multiple import
statements are valid. * indicates that the compiler should search this entire package hierarchy when it
encounters a class name.
example: import [Link];
here java is main package, util is subordinate package Date is the class belongs to util package

Package Naming conventions


Naming Convention

A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package,
variable, method, etc..).

Package naming convention

 Package names should be hierarchical with the components separated by period.


 Components should consist of lowercase alphabetic characters and rarely digits.
 The name of any package used outside your organization should begin with organization's internet
domain name with the top level domain first, for example [Link], [Link], gov etc.
 The standard libraries and optional packages whose names begin with java.
 Users should not create packages whose names start with java.
 The package name should be unique.

 Creating and Importing Packages


A Java package is simply a directory that contains one or more class files. The task of creating and
accessing user defined package can be summarized as
 Creating a new folder in the name of package. The location of packages are defined by using the
CLASSPATH environmental variable
 Moving the class file to the new folder. Each class in the package must have the following as its first
line:
Package <package name>;
 Calling the package from any applications .The classes in the package are loaded into a Java application
by using:
import <package name>.* ;
Creating and Accessing a Java Package
Step1 : (Create the folder)
The first step is (rather obviously) to create the directory for the package. The directory is created in the
root directory where your application is working. The name of the folder should be same as that of the
package you want to create.
C:\jdk1.3\bin>md pack1
Step 2: (Putting the class inside the package)
Create the class or interface that you are going to keep in the package. The class or interface definition
should begin with the package statement as the first statement.
Syntax:
package package-name;
class definition
or
interface definition
If you want to use the class outside the package where it is defined specify the access specifier as public.
Example:
Step 3:(Save the java file)
Save the source file in the directory created with .java as extension.
(Save as C:\jdk1.3\bin\pack1\[Link])
Step 4: (Compile the java file in the package to create the class file)
Compile the source file from its directory.
(c:\jdk1.3\bin\pack1\javac [Link])
Step 5: (Move to parent Directory)
Return to parent directory
(D:\java\pack1\cd..)
Step 6: (Importing the package)
The package created can be imported into the current source file using the import statement.
Syntax:
import packageName1[.subPackName….].*;
Step 7:
Key in the main program and save it with .java as extension in the root directory. We can now create
references to the classes specified in the package just like other classes and use them in our program.
Example program(user defined package):
[Link]
package siet;
public class packEg
{
public void display()
{
[Link](“WELCOME TO SWARNANDHRA INSTITUE”);
}
}
[Link]
import [Link];
class Display
{
public static void main(String ar[])
packEg p = new packEg();
[Link]();
}
}
now we will get output as “WELCOME TO SWARNANDHRA INSTITUE”
Differences between classes and interfaces
CLASSES INTERFACE
 classes have instance variables and their  Using the keyword interface, we can fully abstract
methods have body. a class interface from its implementation
 Interfaces are syntactically similar to classes, but
they lack instance variable, and their methods are
declared without anybody. Once it is defined, any
number of classes can implement an interface.
Also, once class can implement any number of
interfaces.
 An interface defines only abstract methods and
 A class can implement many different final fields i.e., they don’t specify any code for
interfaces. implementing these methods and data fields
contain only constants.

 In abstract class, the methods can have  All methods in an interface are abstract. Which
code/implementation within it. Atleast one means all methods must be empty; no code
method must be abstract. implemented.

 Abstract classes are extended(extends  Interfaces are implemented(implements keyword)


keyword)

Thread

 A thread is a single sequential flow of control within a program.


 Thread uses a separate execution environment.
 Every thread has its own program counter and stack but they can share memory and opened files.
 A thread itself is not a program; it cannot run on its own. Rather, it runs within a program.

Multithreading

 A program that contains multiple flow of control is known a multithreaded program.


 Multithreading allows a running program to perform several task at the same time. Java uses
threads to enable the entire environment to be asynchronous. It makes maximum use of CPU
because idle time(waiting time) can be kept to minimum. This helps to reduce the wastage of
CPU life cycle.
 The java runtime system depends on threads for many things and all class libraries are
designed with multithreading in mind. A thread exists in several states.
o Running Thread
o Ready to run as soon as it gets CPU time
o Suspended thread
o Suspended thread can be resumed
o Thread can be blocked

o Thread can be terminated

Properties of single threaded program


 The process begins execution at a well-known point. In Java the thread begins execution at the first
statement of the function or method called main().
 Execution of the statements follows in a completely ordered, predefined sequence for a given set of
inputs.
 While executing, the process has access to certain data. In Java, there are three types of data a process
can access: local variables are accessed from the thread's stack, instance variables are accessed
through object references, and static variables are accessed through class or object references.
Multithreading
 In Multithreaded programming the process is divided into smaller independent tasks that can be
simultaneously executed.
 In every program there will be at least only thread running and it is called the main thread.

 Creating Thread
The thread class in the [Link] package allows to create and manages threads. There are two ways of
creating a thread in java
1. Extending the class thread
2. Implementing runnable interface
1. Extending the class thread
Define the class that extends thread class and overrides its run() method in the subclass. Each thread is a
separate instance of the class.
Syntax:
class classname extends Thread
{
-------
-------
public void run()
{
//statements
}
}
3. Create an instance of the subclass.
4. Call the start( ) method of class Thread. The start( ) calls run() method.
Syntax:
Classname obj=new classname();
[Link]();

2. Implementing Runnable interface


The runnable interface calls run() method to implement threads in our program.
Syntax:
class classname implements Runnable
{
-------
-------
public void run()
{
//statements
}
}
3. Create an instance of the implemented class.
4. Instantiate an object of class Thread using the constructor with the runnable object as the parameter.
5. Call the start( ) method using the Thread object. This in turn will call the run( ) method.
Syntax:
classname obj=new classname();
Thread threadobj=new Thread(obj);
[Link]();
Example :
Import [Link].*;
Import [Link].*;
class ThreadX implements Runnable
{
public void run()
{
for(int i=1;i<=4;i++)
{
[Link](“Thread x:”+i);
} } }
class RunnableDemo
{
public static void main(String args[J])
{
Thread x=imp = new Theadx();
Thread Thready = new Thread(imp)
[Link]();
}
}
 Stopping and Blocking a Thread
Stopping a Thread :
 We want to stop a thread from running, by calling its stop() method like [Link]();
 The stop() method used the premature death of a thread.
Blocking a Thread :
 A thread can also be temporarily suspending or blocking from entering into the runnable and
subsequently running state by using either of the following thread methods
1. Sleep() - Blocked for a specified time
2. Suspend() – Blocked until further orders
3. Wait() – Blocked until certain condition occurs.
 These methods cause the thread to go into the blocked state. The thread will return to the runnable
state when the specified time is elapsed in the case of sleep(), the resume() method is invoked in the
case of suspend() and the notify() method is called in the case of wait().
 Life Cycle of a Thread
Thread States:
 A thread moves through several states from its creation to its termination. The life cycle of a thread,
consists of five shows,
1. New born state
2. Ready to run state
3. Running state
4. Blocked state
5. Dead state

1. New born state


A thread is said to be newborn when we create an object of the class thread
2. Runnable state
A thread is ready for execution and waits for the processor to be available
3. Running state
A thread comes to this state when it starts its execution
4. Blocked state
A thread comes to this state when it is made to stop its execution
5. Dead state
A thread comes to this state when it completes its execution.

New Born state


 The thread enters the new born state as soon as it is created. The thread is created using the new
operator.
 From the new born state the thread can go to ready to run mode or dead state.
 If start( ) method is called then the thread goes to ready to run mode. If the stop( ) method is called
then the thread goes to dead state.

Ready to run mode (Runnable Mode)


 If the thread is ready for execution but waiting for the CPU the thread is said to be in ready to run
mode.
 All the events that are waiting for the processor are queued up in the ready to run mode and are
served in FIFO manner or priority scheduling.
 From this state the thread can go to running state if the processor is available using the scheduled( )
method.
 From the running mode the thread can again join the queue of runnable threads.
 The process of allotting time for the threads is called time slicing.

Running state
 If the thread is in execution then it is said to be in running state.
 The thread can finish its work and end normally.
 The thread can also be forced to give up the control when one of the following conditions arise
1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by using the
resume() method.
2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method. The sleeping
method re-enters runnable state when the time elapses.
3. A thread can be made to wait until a particular event occur using the wait() method, which can be run
again using the notify( ) method.
Blocked state
 A thread is said to be in blocked state if it prevented from entering into the runnable state and so the
running state.
 The thread enters the blocked state when it is suspended, made to sleep or wait.
 A blocked thread can enter into runnable state at any time and can resume execution.
Dead State
 The running thread ends its life when it has completed executing the run() method which is called
natural dead.
 The thread can also be killed at any stage by using the stop( ) method.
 Methods in Thread class
The Thread class has methods that can be used to control the behaviour of threads. There are two
constructors in thread class
 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()
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)
10. getPriority( ) method
This method is used to get the priority of the thread.
Syntax
int getPriority( )
 Thread Priority
 The user can set the priority for threads. This concept is called thread priority. This is done by using the
method setPriority( ) , which is a member of thread class. The general form is ,
final void setPriority ( int level );
where ,
final,void – keywords
setPriority – method
level - priority level

 There are three types of thread priorities :


 Minimum – priority = 1
 Normal – priority = 5
 Maximum – priority = 10

Whenever a new Java thread is created it has the same priority as the thread which created it. Thread
priority can be changed by the setpriority() method.
Syntax:
void setPriority(int P)
The getPriority( ) method is used to get the priority of the thread.
Syntax
int getPriority( )
 Thread Scheduling
 Execution of multiple threads in some order on a single CPU system is called scheduling. Java uses
fixed-priority scheduling algorithms to decide which thread to execute the thread with the highest
priority runs first.
 If another thread with a higher priority is started, Java makes the lower priority thread wait . If more
than one thread exists with the same priority, Java quickly switches between them in Round-Robin
Fashion But only if the operating system uses time-slicing.
 The above act as a guide to scheduling however the actual implementation depends on the Operating
System. Most operating systems use one of two scheduling methods Preemptive scheduling or Time
slicing.
 In preemptive scheduling the highest priority thread continues to run until it dies, waits, or is
preempted by a thread of higher priority . In time slicing a thread runs for a specific time and then
enters the runnable state; at which point the scheduler decides whether to return to the thread or
schedule a different thread.
Example :
Let T1, T2, T3, ……….,T10 be different threads . Let their priorities be
T1 -10 T6 -10
T2 -8 T7 -8
T3 -10 T8 -6
T4 -7 T9 -6
T5 -9 T10 -2
The table below shows the scheduling of the above threads.

 Thread Synchronization
 In multithreaded application, multiple threads might access the data and call methods simultaneously
and this may create problems such as violation of data and unpredictable result. These problems are
referred to as concurrency problems.
 Synchronization is the technique that can be used to overcome the concurrency problem that may
arise when two or more threads need to access the shared resources.
 Java uses the concept of semaphores (also called monitors) for synchronization. This is similar to a lock.
Whenever a thread is making an attempt to use shared resources, it will lock the resource (if it is free)
and then after using, it will release (open the lock ) the resource.
 The keyword synchronized in Java is used for synchronization. This keyword can be used in two ways
ie., a method can synchronized or a block of code can be synchronized.
Syntax:
synchronized void update {
……………….
……………… //code here is synchronized
……………..
}
Concept of monitor
 When we declare a method synchronized, java creates a “monitor” and hands it over to the thread
that calls the method first time.
 As long as the thread holds the monitor, no other thread can enter the synchronized section of the
code. A monitor is like a key and the thread that holds the key can only open the lock.
 Whenever a thread has completed its work of using synchronized method, it will hand over the
monitor to the next thread that is ready to use the same resource.
 An interesting situation may occur when two or more threads are waiting to gain control of a resource.
Due to some reasons, the condition on which the waiting threads rely on the gain control does not
happen. This results in what is known as deadlock.
Example of Synchronization:
class A extends Thread {
synchronized public void run() {
for(int i=0;i<5;i++) {
[Link]("\t From Thread A :i="+i);
}
[Link]("Exit from A");
}
}
class B extends Thread {
synchronized public void run() {
for(int j=0;j<5;j++) {
[Link]("\t From Thread B :j="+j);
}
[Link]("Exit from B");
}
}
class C extends Thread {
synchronized public void run()
{
for(int k=0;k<5;k++)
{
[Link]("\t From Thread C :k="+k);
}
[Link]("Exit from C");
}
}
class SynchronizedTest
{
public static void main(String args[])
{
A objA=new A();
B objB=new B();
C objC=new C();
[Link]("Start Thread A");
[Link]();
[Link]("Start Thread B");
[Link]();
[Link]("Start Thread C");
[Link]();
[Link]("End of main Thread");
}
}

You might also like