SlideShare a Scribd company logo
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve www.javatpoint.com/abstract-class-in-java There can be
only abstract methods in the Java interface, not method body. It is used to achieve abstraction and
multiple www.javatpoint.com/inheritance-in-java
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given below. o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance. o It can be used to achieve loose
coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and
abstract.
+ compiler-►
interface Pnntable{ interface Pnntable{
nt M N=5 public static final int MIN=5
void print): public abstract void printn:
Prints blejava Printable .class
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface,
but a class implements an interface.
class interface interface
ik
extends
4
1 implements
ii
extends
class class interface
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in the A6
class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void
print(){System.out.println(MHelloM);}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.printO;
10. }
11. }
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void
show(){System.out.println(MWelcomeM);}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14.
obj.show();
15. }
16. }
Multiple inheritance is not supported through class in java, but it is possible by an
interface
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of
www.javatpoint.com/object-and-class-in-javabecause of ambiguity. However, it is supported in case of an
interface because there is no ambiguity. It is because its implementation is provided by the
implementation class. For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new
TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }
Object Oriented
Programming in Java
By
Dr Rani Reddy
Object Oriented Programming
Concepts in Java
Object oriented Programming is a paradigm
or organizing principle for software, where
the program is structured according to the
information it manipulates, rather than the
operations it does. Data, not procedures,
shape the program.
What is an Object ?
An Object is defined as a software
package that incorporates a set of
related data and all the functions
needed to manipulate this data. The
related set of data, the data members,
captures the state of an object.
Defining Objects : STATE (Attributes)
Encompasses all of the properties of an
object. Each property has a value. All
objects of the same type have same
properties ( although they may have
different values).
Properties are implemented with Object
Variables or instance variables .
A motorcycle class might include the
following attributes and have these typical
values:
• color : red, green, silver, brown
• style : cruiser, sport bike, standard
• Make : Honda, BMW, Bultaco
Here color, style, make are the instance
variables.
Example :
Defining Objects : BEHAVIOR
Is how an object reacts, in terms of state
changes and interaction with the other
objects.
Behavior is the only way objects can do
anything to themselves or have anything
done to them.
A motorcycle class might have some
behavior like:
• Start the engine
• Stop the engine
• Speed up
• Change gear
• Stall
Example :
Defining Objects : BEHAVIOR
The behavior is defined by the use of
functions which are confined to a Class and
are called member functions or Methods.
Classes
A class is a set of objects that share the same
properties and behavior.
Its where state and behavior of objects is
defined through Variables and Methods.
Example:
Every Motorcycle is defined in the
Motorcycle class.
class Motorcycle {
String make;
String color;
boolean enginestate = false;
void startEngine() {
if (enginestate = = true)
Example of the Motorcycle Class
System.out.println (“The engine is
already on”)
else {
enginestate = true;
System.out.println ( “The engine is
now on”);
}
}
}
public static void main (String args[] )
{
Motorcycle m = new Motorcycle();
m.make = “Yamaha RZ350”;
m.color = “Yellow”;
System.out.println(“Calling
showAtts…”);
m.showAtts();
The main() method for Motorcycle
class
System.out.println (“………………”);
System.out.println(“Starting Engine …”);
m.startEngine();
System.out.println (“………………”);
System.out.println(“Calling showAtts…”);
m.showAtts();
System.out.println (“………………”);
System.out.println(“Starting Engine …”);
m.startEngine(); }
class Motorcycle {
String make;
String color;
boolean enginestate = false;
void startEngine() {
if (enginestate = = true)
System.out.println (“The engine is
already on”)
The final version of Motorcycle.java
file
else {
enginestate = true;
System.out.println ( “The engine is now
on”);
}
}
void showAtts () {
System.out.println (“This motorcycle is a”
+color+ “ ” +make);
if (engineState = = true)
System.out.println (“The engine is on.”);
else System.out.println (“The engine is
off.”);
}
public static void main (String args[] ) {
Motorcycle m = new Motorcycle();
m.make = “Yamaha RZ350”;
m.color = “Yellow”;
System.out.println(“Calling showAtts…”);
m.showAtts();
System.out.println (“………………”);
System.out.println(“Starting Engine …”);
m.startEngine();
System.out.println (“………………”);
System.out.println(“Calling showAtts…”);
m.showAtts();
System.out.println (“………………”);
System.out.println(“Starting Engine …”);
m.startEngine(); } }
The three major concepts in OOP
are:
• Encapsulation
• Inheritance
• Polymorphism
Encapsulation
Embedding both data and code into a
single entity.
•Allows us to use data hiding which is a
way to prevent direct access to the
variables in an object.
• Separates the interface to the class from
its implementation.
Class Flight
{
int altitude;
private int heading;
int speed;
float latitude;
float longitude;
// change the flight’s heading by angle
degrees
void turnFlight (int angle) {
heading = (heading + angle) % 360;
// make sure angle is in the range 0-359
degrees
if (heading < 0) heading = heading + 360;
}
void setHeading (int angle) {
heading = angle % 360;
// make sure angle is in the range 0-359
degrees
if (heading < 0) heading = heading + 360;
}
int getHeading( ) {
return heading;
}
// print information about the flight
void printFlight () {
System.out.println(altitude + “ / ” +
heading + “ / ” + speed);
}
}
Inheritance
Inheritance is the process by which
one object acquires the properties of
another object.
Benefits of Inheritance
•Subclasses provide specialized behaviors from the
basis of common elements provided by the
superclass. Through the use of inheritance,
programmers can reuse the code (in the superclass)
many times.
• Programmers can implement superclasses called
abstract classes that define “generic” behaviors. The
abstract superclass defines and may partially
implement the behavior but much of the class is
undefined and unimplemented. Other programmers
fill in the details with specialized subclasses.
Example of Inheritance
class CommercialFlight extends Flight {
// extra members in CommercialFlight
int flightNumber;
int passengers;
}
The Commercial
Flight Class
inherits member
variables and
functions from
Flight, and then
adds its own
member variables.
Polymorphism
Polymorphism is the ability of a single
function name to be used to operate on
many different types. It is a feature that
allows one interface to be used for a general
class of actions. The specific action is
determined by the exact nature of the
situation.
Polymorphism
• We can deal with objects without the
need to know what exact class they belong
to.
• This is an extension of the inheritance
concept.
JAVA - PACKAGES:
What is package:
Packages are used in Java, in-order to avoid name conflicts and to control access of
class, interface and enumeration etc. A package can be defined as a group of similar
types of classes, interface, enumeration or sub-package.
Using package it becomes easier to locate the related classes and it
also provides a good structure for projects with hundreds of classes and other files.
Benefits of using package in java:
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) This packages can be provide reusability of code.
5) We can create our own package or extend already available package.
Java Packages: Types:
• Built-in Package: Existing Java package for
example java.lang, java.util ,java.io etc.
• User-defined-package: Java package created by user to categorize their
project's classes and interface.
How to Create a package:
Creating a package in java is quite easy. Simply include a package command
followed by name of the package as the first statement in java source file.
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the project directory.
Java uses file system directories to store packages. For example the .java file for any
class you define to be part of mypackage package must be stored in a directory
called mypackage.
Additional points about package:
• A package is always defined as a separate folder having the same name as the
package name.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the package must be
declared public.
• All classes within the package must have the package statement as its first line.
• All classes of the package must be compiled before use (So that they are error
free)
Example of Java packages:
Package mypack; public class Simple {
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to compile Java packages:
This is just like compiling a normal java program. If you are not using any IDE, you
need to follow the steps given below to successfully compile your packages:
1. java -d directory javafilename For example javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If
you want to keep the package within the same directory, you can use . (dot).
How to run java package program:
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java To Run: java mypack.Simple
Output: Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package:
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*:
//save by A.java package pack; public class A
{
public void msg()
{
System.out.println("Hello java");}
}
//save by B.java package mypack; import pack.*; class B
{
public static void main(String args[])
{
A obj = new A(); obj.msg();
}
}
Output: Hello java
2) Using packagename.classname:
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname:
//save by A.java
package pack; public class A
{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java package mypack; import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A(); obj.msg();
}
}
Output: Hello
3) Using fully qualified name:
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Example of package by import fully qualified name:
//save by A.java package pack; public class A
{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java package mypack; class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name obj.msg();
}
}
Output: Hello
Note: If you import a package, subpackages will not be imported.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Subpackage in java:
Package inside the package is called the subpackage. It should be created to
categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun
has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
package com.javatpoint.core; class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple Output: Hello subpackage
How to send the class file to another directory or drive:
There is a scenario, I want to put the class file of A.java source file in classes folder of
c: drive.
For example:
//save as Simple.java package mypack; public class Simple {
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:sources> javac -d c:classes Simple.java To Run:
To run this program from e:source directory, you need to set classpath of the directory
where the class file resides. e:sources> set classpath=c:classes;.; e:sources> java
mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
e:sources> java -classpath c:classes mypack.Simple
Output: Welcome to package
Basics of a thread
As with the Java concepts, everything about thread are defined in a class Thread. The Thread
class encapsulates all of the control one will need over threads. The Thread class is our only
link to manage how threads behave. In this Section, we will learn about : how to create and run
a thread, the life cycle of a thread, and the thread controlling methods.
Creating and Running a Thread
There are two ways to define a thread: one is sub classing Thread and other is using the
Runnable interface.
Using the sub classing thread : With this method, we have to define a class as a sub class of
the Thread class. This sub class should contain a body which will be defined by a method run().
This run() method contains the actual task that the thread should perform. An instance of this
sub class is then to be created by a new statement, followed by a call to the thread's start()
method to have the run() method executed. Let us consider the Illustration 6.1 which includes a
program to create there individual threads that each print out their own " Hello World !" string.
Illustration 6.1 // Creating and running threads using sub
classing Thread //
/* Creating three threads using the class Thread and then running them concurrently.
*/
class ThreadA extends Thread{ public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("From Thread A with i = "+ -1*i);
}
System.out.println("Exiting from Thread A ...");
}
}
class ThreadB extends Thread { public void run( ) {
for(int j = 1; j <= 5; j++) {
System.out.println("From Thread B with j= "+2* j);
}
System.out.println("Exiting from Thread B ...");
}
}
class ThreadC extends Thread{ public void run( ) {
for(int k = 1; k <= 5; k++) {
System.out.println("From Thread C with k = "+ (2*k-1));
}
System.out.println("Exiting from Thread C ...");
}
}
public class Demonstration_111 {
public static void main(String args[]) {
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
ThreadC c = new ThreadC();
a. start();
b. start();
c. start();
System.out.println("... Multithreading is over ");
}
}
OUTPUT:
From Thread A with i = -1
From Thread A with i = -2
From Thread A with i = -3
From Thread B with j= 2
From Thread A with i = -4
From Thread A with i = -5
Exiting from Thread A
... Multithreading is over
From Thread C with k = 1
From Thread B with j= 4
From Thread B with j= 6
From Thread B with j= 8
From Thread B with j= 10
Exiting from Thread B
... From Thread C with k
= 3 From Thread C with k
= 5 From Thread C with k
= 7 From Thread C with k
= 9 Exiting from Thread
C ...
In the above simple example, three threads (all of them are of some type) will be executed
concurrently. Note that a thread can be directed to start its body by start() method.
Using the Runnable interface : A second way to create threads is to make use of the
Runnable interface. With this approach, first we have to implement the Runnable
interface.[Runnable interface is already defined in the system package java.lang with a single
method run() as below :
public interface Runnable {
public abstract void run( );
} ]
When we will create a new thread, actually a new object will be instantiated from this Runnable
interface as the target of our thread, meaning that the thread will look for the code for the run( )
method within our object's class instead of inside the Thread's class. This is illustrated with an
example where two processes Brother and Sister will be executed simultaneously.
Illustration 6.2
/* Creating three threads using the Runnable interface and then running them
concurrently. */
class ThreadX implements Runnable{ public void run( ) {
for(int i = 1; i <= 5; i++) {
System.out.println("Thread X with i = "+ -1*i);
}
System.out.println("Exiting Thread X ...");
}
}
class ThreadY implements Runnable { public void run( ) {
for(int j = 1; j <= 5; j++) {
System.out.println("Thread Y with j = "+ 2*j);
}
System.out.println("Exiting Thread Y ...");
}
}
class ThreadZ implements Runnable{ public void run( ) {
for(int k = 1; k <= 5; k++) {
System.out.println("Thread Z with k = "+ (2*k-
1));
}
System.out.println("Exiting Thread Z ...");
}
}
public class Demonstration_112 {
public static void main(String args[]) {
ThreadX x = new ThreadX();
Thread t1 = new Thread(x);
ThreadY y = new ThreadY();
Thread t2 = new Thread(y);
//ThreadZ z = new ThreadZ();
//Thread t3 = new Thread(z);
Thread t3 = new Thread(new ThreadZ());
t1.start();
t2.start();
t3.start();
System.out.println("... Multithreading is over ");
}
}
OUTPUT:
Thread X with i = -1
Thread X with i = -2
Thread Z with k = 1 Thread
Z with k = 3 Thread Z with
k = 5 Thread Z with k = 7
Thread Z with k = 9
Exiting Thread Z ...
... Multithreading is over
Thread Y with j = 2 Thread
Y with j = 4 Thread Y with
j = 6 Thread Y with j = 8
Thread Y with j = 10
Exiting Thread Y ...
Thread X with i = -3
Thread X with i = -4
Thread X with i = -5
Exiting Thread X ...
Note : Note in the above example, how after implementing objects, their thread is created and
their threads start execution. Also note that, a class instance with the run( ) method defined
within must be passed in as an argument in creating the thread instance so that when the start()
method of this Thread instance is called, Java run time knows which run() method to execute.
This alternative method of creating a thread is useful when the class defining run() method
needs to be a sub class of other classes; the class can inherit all the data and methods of the
super class.
Life cycle of threads
Each thread is always in one of five states, which is depicted in Figure 6.1
Figure 6.1 : Five states of a thread
Newborn : When a thread is created (by new statement ) but not yet to run, it is called in
Newborn state. In this state, the local data members are allocated and initialized.
Runnable : The Runnable state means that a thread is ready to run and is awaiting for the
control of the processor, or in other words, threads are in this state in a queue and wait their
turns to be executed.
Running : Running means that the thread has control of the processor, its code is currently
being executed and thread will continue in this state until it get preempted by a higher priority
thread, or until it relinquishes control.
Blocked : A thread is Blocked means that it is being prevented from the Runnable ( or Running)
state and is waiting for some event in order for it to reenter the scheduling queue.
Dead : A thread is Dead when it finishes its execution or is stopped (killed) by another thread.
Threads move from one state to another via a variety of means. The common methods for
controlling a thread's state is shown in Figure 6.1. Below, we are to summarize these methods :
start ( ) : A newborn thread with this method enter into Runnable state and Java run time create
a system thread context and starts it running. This method for a thread object can be called
once only
stop( ) : This method causes a thread to stop immediately. This is often an abrupt way to end a
thread.
suspend( ) : This method is different from stop( ) method. It takes the thread and causes it to
stop running and later on can be restored by calling it again.
resume ( ) : This method is used to revive a suspended thread. There is no gurantee that the
thread will start running right way, since there might be a higher priority thread running already,
but, resume()causes the thread to become eligible for running. sleep (int n ) : This method
causes the run time to put the current thread to sleep for n milliseconds. After n milliseconds
have expired, this thread will become elligible to run again. yield( ) : The yield() method causes
the run time to switch the context from the current thread to
the next available runnable thread. This is one way to ensure that the threads at lower priority
do not get started.
Other methods like wait(), notify(), join() etc. will be discussed in subsequent discussion. Let
us illustrate the use of these method in a simple Application.
Illustration 6.3
/* Demonstration of thread class methods : getID() */
/* Java code for thread creation by extending the Thread class */
class ThreadId extends Thread { public void run() { try {
// Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() + "
is
running");
}
catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Demonstration_113{
public static void main(String[] args)
{
int n = 8; // Number of threads for (int i=0; i<8; i++)
{
ThreadId object = new ThreadId(); object.start();
}
}
}
OUTPUT:
Thread 21
Thread 22
Thread 23
Thread 25
Thread 26
Thread 27
Thread 24
Thread 28
s running
s running
s running
s running
s running
s running
s running
s running
Illustration 6.4
/* Demonstration of thread class methods : getID() */
/* Java code for thread creation by implementing the Runnable Interface */
class ThreadId implements Runnable {
public void run() { try {
// Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() + "
is
running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
class Demonstration_114 {
public static void main(String[] args)
{
int n = 8; // Number of threads for (int i=0; i<8; i++){
Thread object = new Thread(new
ThreadId()); object.start();
}
}
}
OUTPUT:
Thread 21
Thread 23
Thread 24
Thread 25
Thread 22
Thread 27
Thread 26
Thread 28
s running
s running
s running
s running
s running
s running
s running
s running
Illustration 6.5
/* Use of yield(), stop() and sleep() methods */
class ClassA extends Thread{ public void run() {
System.out.println("Start Thread A ...."); for(int i
= 1; i <= 5; i++) { if (i==1) yield();
System.out.println("From Thread A: i = "+
i);
}
System.out.println("... Exit Thread A");
}
}
class ClassB extends Thread{ public void run() {
System.out.println("Start Thread B ...."); for(int j
= 1; j <= 5; j++) {
System.out.println("From Thread B: j = "+
j); if (j==2) stop();
}
System.out.println("... Exit Thread B");
}
}
class ClassC extends Thread{ public void run() {
System.out.println("Start Thread C ...."); for(int k
= 1; k <= 5; k++) {
System.out.println("From Thread B: j = "+
k); if (k==3){
try{
sleep(1000);
}catch(Exception e){}
}
}
System.out.println("... Exit Thread C");
}
}
public class Demonstration_115{
public static void main (String args[]) {
ClassA t1 = new ClassA();
ClassB t2 = new ClassB();
ClassC t3 = new ClassC(); t1.start();
t2.start(); t3.start();
System.out.println("... End of executuion
");
}
}
From Thread A: i = 3
From Thread A: i = 4
From Thread A: i = 5
... Exit Thread A
From Thread B: j = 2
From Thread B: j = 3
From Thread B: j = 4
From Thread B: j = 5
... Exit Thread C
Illustration 6.6
/* Use of suspend() and resume() methods */
class Thread1 extends Thread { public void run( ) { try{
System.out.println (" First thread starts running" );
sleep(10000);
System.out.println (" First thread finishes running" );
}
catch(Exception e){ }
}
}
class Thread2 extends Thread { public void run( ) { try{
System.out.println ( "Second thread starts running");
System.out.println ( "Second thread is suspended itself
"); suspend( );
}
System.out.println (" Second thread runs again" );
catch(Exception e){ }
}
}
class Demonstration_116{
public staticvoid main (String args[ ] ){
try{
i.e. in Newborn state
Thread1 first = new Thread1( ); // It is a newborn thread
Thread2 second= new Thread2( ); // another new born thread
first.start( ); // first is scheduled for running
second.start( ); // second is scheduled for running
is suspended
System.out.println("Revive the second thread" ); // If it
second.resume( );
" );
System.out.println ("Second thread went for 10 seconds sleep
second.sleep (10000);
running" );
System.out.println ("Wake up second thread and finishes
System.out.println ( " Demonstration is finished ");
}
catch(Exception e){ }
}
}
OUTPUT:
Revive the second thread First thread
starts running Second thread starts
running Second thread is suspended itself
Second thread went for 10 seconds sleep
Status of a Thread
It is some time essential to know some information about threads. There are number of methods
defined in Thread which can be called for getting information about threads. Some of the most
commonly used methods for thread's status are listed here :
currentThread( ) : The CurrentThread() is a static method returns the Thread object which is the
currently running thread.
setName( String s) : The SetName() method is to assign a name s for a thread prior its
execution. This, therefore, identifies the thread with a string name. This is helpful for debugging
multi-threaded programs.
getName( ) : This method returns the current string value of the thread's name as set by
SetName().
setPriority (int p) : This method sets the thread's priotity to an integer value p passed in. There
are several predefined priotiry constants defined in class Thread : MIN-PRIORITY, NORM-
PRIORTY and MAX-PRIORITY, which are 1, 5, and 10 respectively.
getPriority ( ) : This method returns the thread's current priority, a value between 1 and 10.
isAlive ( ) : This method returns true if the thread is started but not dead yet.
isDaemon ( ) : This method returns true if the thread is a daemon thread.
Following is the Illustration 6.7 to give an idea how the above mentioned method may be
utilized.
Illustration 6.7 // Status information of threads //
/* Setting priority to threads */
class ClassA extends Thread{ public void run() {
System.out.println("Start Thread A ...."); for(int i = 1; i
<= 5; i++) {
System.out.println("From Thread A: i = "+ i);
}
System.out.println("... Exit Thread A");
}
}
class ClassB extends Thread{ public void run() {
System.out.println("Start Thread B ...."); for(int j
= 1; j <= 5; j++) {
System.out.println("From Thread B: j = "+
j);
}
System.out.println("... Exit Thread B");
}
}
class ClassC extends Thread{ public void run() {
System.out.println("Start Thread C ...."); for(int k
= 1; k <= 5; k++) {
System.out.println("From Thread B: j = "+
k);
}
System.out.println("... Exit Thread C");
}
}
class Demonstration_117{
public static void main (String args[]) {
ThreadA t1 = new ThreadA();
ThreadB t2 = new ThreadB();
ThreadC t3 = new ThreadC();
t3.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(t2.getPriority() + 1);
t1.setPriority(Thread.MIN_PRIORITY);
t1.start(); t2.start(); t3.start();
System.out.println("... End of executuion
");
}
}
OUTPUT:
Start Thread A ....
From Thread A: i = 1
From Thread A: i = 2
From Thread A: i = 3
From Thread A: i = 4
From Thread A: i = 5
... Exit
Thread
A
... End of executuion
Start Thread B ....
Start Thread C ....
From Thread B: j = 1
From Thread B: j = 2
From Thread B: j = 3
From Thread B: j = 4
From Thread B: j = 5
... Exit
Thread
B
From Thread B: j = 1
From Thread B: j = 2
From Thread B: j = 3
From Thread B: j = 4
From Thread B: j = 5
... Exit Thread C
Illustration 6.8
/* Data race example. */
public class Demonstration_118 extends Thread {
public static int x; public void run() {
for (int i = 0; i < 100; i++) { x = x +
1;
}
x = x - 1;
}
}
public static void main(String[] args) { x
= 0;
for (int i = 0; i < 1000; i++){ new
Demonstration_118().start();
System.out.println(x);
}
}
// x not always 0!
Synchronization and Inter-Thread Communication
It is already mentioned that threads in Java are running in the same memory space, and hence
it is easy to communicate between two threads. Inter-thread communications allow threads to
talk to or wait on each other. Again, because all the threads in a program share the same
memory space, it is possible for two threads to access the same variables and methods in
object. Problems may occur when two or more threads are accessing the same data
concurrently, for example, one thread stores data into the shared object and the other threads
reads data, there can be synchronization problem if the first thread has not finished storing the
data before the second one goes to read it. So we need to take care to access the data by only
one thread process at a time. Java provides unique language level support for such
synchronization. in this Section we will learn how synchronization mechanism and inter-thread
communications are possible in Java.
Synchronization
To solve the critical section problem, one usual concept is known what is called monitor. A
monitor is an object which is used as a mutually exclusive lock ( called mutex). Only one thread
may own a monitor at a given time. When a thread acquires a lock it is said to have entered the
monitor. All other threads attempting to enter the locked monitor will be suspended until the
owner thread exits the monitor. But in Java, there is no such monitor. In fact, all Java object
have their own implicit monitor associated with them. Here, the key word synchronized is used
by which method (s) or block of statements can be made protected from the simultaneous
access. With this, when a class is designed with threads in mind, the class designer decides
which methods should not be allowed to execute concurrently. when a class with synchronized
method is instantiated, the new object is given its own implicit monitor. The entire time that a
thread is inside of a synchronized method, all other threads that try to call any other
synchronized method on the same instance have to wait. In order to exit the monitor and
relinquish control of the object to the next waiting thread the monitor owner simply needs to
return from the method.
Let us illustrate this mechanism with a simple example.
Suppose, we want to maintain a bank account of customers. Several transactions, such as
deposite some amount to an account and withdraw some amount from an account etc. are
possible. Now, for a given account, if two or more transactions come simultaneously then only
one transaction should be allowed at a time instead of simulataneous transaction processing so
that data inconsistency will never occur. So, what we need is to synchronize the transaction.
Illustration 6.9 is to implement such a task.
Illustration 6.9
/* The following Java application shows how the transactions in a bank can be carried
out concurrently. */
class Account {
public int balance;
public int accountNo;
void displayBalance() {
System.out.println("Account No:" + accountNo + "Balance: " +
balance);
}
synchronized void deposit(int amount){
balance = balance + amount;
System.out.println( amount + " is deposited");
displayBalance();
}
synchronized void withdraw(int amount){
balance = balance - amount;
System.out.println( amount + " is
withdrawn"); displayBalance();
}
}
class TransactionDeposit implements Runnable{ int
amount;
Account accountX;
TransactionDeposit(Account x, int amount){
accountX = x; this.amount =
amount; new Thread(this).start();
}
}
public void run(){
accountX.deposit(amount);
}
class TransactionWithdraw implements Runnable{
int amount;
Account accountY;
TransactionWithdraw(Account y, int amount) {
accountY = y; this.amount = amount;
new Thread(this).start();
}
public void run(){
accountY.withdraw(amount);
}
}
class Demonstration_119{
public static void main(String args[]) {
Account ABC = new Account();
ABC.balance = 1000;
ABC.accountNo = 111;
TransactionDeposit t1;
TransactionWithdraw t2; t1 = new
TransactionDeposit(ABC, 500); t2 =
new TransactionWithdraw(ABC,900);
}
}
In the above example, the keyword synchronized is used for the methods void deposite(..) and
void withdraw(^) so that these two methods will never run for the same object instance
simultaneously.
Alternatively, if one wants to design a class that was not designed for multi-thread access and
thus has non-synchronized methods, then it can be wrapped the call to the methods in a
synchronized block. Here is the general form of the synchronized statement :
synchronized (Object ) { block of statement(s) }
where Object is any object reference. For example, make all the methods in Account class as
non-synchronized (remove the synchronized key word). Then modify the code for run( ) in class
TransactionDeposite and class TransactionWithdraw are as under :
public void run( ) { // in TransactionDeposite
synchronized (accountX ) {
accountX.deposite(amount );
}
}
public void run( ) { //
synchronized (accountY ) {
accountY.withdraw(amount
in TransactionWithdraw
);
}
}
You will get the same output.
Interested reader may try to run the program without using synchronization and observe the
result.
Note: In a class, non-synchronized methods are concurrently executable.
Inter-thread Communication
There are three ways for threads to communicate with each other. The first is through commonly
shared data. All the threads in the same program share the same memory space. If an object is
accessible to various threads then these threads share access to that object's data member and
thus communicate each other.
The second way for threads to communicate is by using thread control methods. There are such
three methods by which threads communicate for each other :
suspend ( ): A thread can suspend itself and wait till other thread resume it.
resume ( ): A thread can wake up other waiting thread (which is waiting using suspend() )
through its resume() method and then can run concurrently.
join ( ) :This method can be used for the caller thread to wait for the completion of called thread.
The third way for threads to communicate is the use of three methods; wait(), notify(), and
notifyAll(); these are defined in class Object of package java.lang. Actually these three
methods provide an elegant inter-process communication mechanism to take care the deadlock
situation in Java. As there is multi-threading in program, deadlock may occur when a thread
holding the key to monitor is suspended or waiting for another thread's completion. If the other
thread is waiting for needs to get into the same monitor, both threads will be waiting for ever.
The uses of these three methods are briefed as below :
wait ( ):This method tells the calling thread to give up the monitor and make the calling thread
wait until either a time out occurs or another thread call the same thread's notify() or notifyAll()
method.
Notify ( ): This method wakes up the only one (first) waiting thread called wait() on the same
object.
notifyAll( ): This method will wake up all the threads that have been called wait( ) on the same
object.
Now, let us demonstrate the classical use of these methods. Illustration 6.6 is for this purpose.
Illustration 6.10 : // Inter thread communication : Producer & Consumer
problem //
class Q {
processes
// Q is a class containing two parallel
int n;
boolean flag = false;
//PRODUCER
synchronized void put( int n) { // Produce a value
if(flag) {
try wait( ); catch(InterruptedException e);
// to the
}
// critical section
this.n = n;
System.out.println( "Produce :" + n);
// Critical Section
flag = true;
// Exit from the
notify( );
// Entr
// crit
}
//CONSUMER
started
synchronized int get( ) { // Consume a value
if(! flag) {
// Entry
try wait( ); catch(InterruptedException e);
// to the
}
// critical section
System.out.println( "Consume :" + n);
// Critical Section
flag = false;
// Exit from the
notify( ); return( n );
}
// crit
class Producer implement Runnable {
Q q;
Producer ( Q q ) {
this.q =q;
new thread (this).start ( )
;
// Thread for Producer process
// constructor
// Producer process is
}
public void run( ) { // infinite running thread for Producer
int i = 0; while (true )
q.put ( i++ );
}
}
class Consumer implement Runnable { // Thread for consumer process
Q q;
Consumer (Q q ) { // Constructor
this.q = q;
new Thread (this).start ( );
}
public void run( ) { // infinite running thread for Consumer
while (true)
q.get ( );
}
}
class PandC {
public static void main( String args[ ] ) {
Q q = new Q( ); // an instance of parallel processes is
created
producer new Producer(q) ;
new Consumer (q);
// Run the thread for
// Run consumer thread
}
}
To understand this critical section problem in operating system design, user may be referred to :
Operating system concept by Peterson and Sylberchotze, Addiction Wesley Inc.
Note : All three methods i.e. wait(), notify(), and notifyAll() must only be called from the inside of
synchronized methods.
Thread Groups and Daemon
There are two other variation in thread class known : ThreadGroup and Daemon. ThreadGroup,
as its name implies, is a group of threads. A thread group can have both threads and other
thread groups as its member elements. In Java, there is a default thread group called
SystemThreadGroup, which is nothing but the Java run time itself. When a Java application is
started, the Java run time creates the main thread group as a member of the system thread
group. A main thread is created in the main thread group to run the main( ) method of the
Application. In fact, every thread instance is member of exactly one thread group. By default, all
new user created threads and thread groups) will become the members of the main thread
group. All the threads and thread in an application form a tree with the system thread group as
the root.
Daemon threads are service threads. They exist to provide service threads. They exist to
provide services to other threads. They normally run in an infinite loop and attending the client
threads requesting services. When no other threads exist daemon thread is automatically
ceased to exist.
A new thread group can be created by instantiating the thread group class. For example,
Threadgroup TG = new ThreadGroup ( ) ;
Thread T = new Thread ( TG) ;
These two statements creates a new thread group TG which contains a thread T as the only
member.
To create a daemon thread, there is a method setDaemon() can be called just after the creation
of a thread and before the execution is started. For example, following two statement is to make
a thread as demon thread.
Thread T = new Thread ( ) ;
T setDaemon (true);
The constructor of the thread is a good candidate for making this method call, Also, by default,
all the threads created by a daemon thread are also daemon thread.
Some commonly used methods for handling thread groups and daemon are listed below :
getName ( ) :Returns the name of the thread group .
setName ( ) :Sets the name of the thread group .
geParent ( ) :Returns the parent thread group of the thread group .
getMaxPriority :Returns the current maximum priority of the thread group.
activeCount ( ) :Returns the number of active threads in the thread group.
activeGroupCount :Returns the number of active threads groups in the
thread group.
isDaemon ( ) :Returns true if the thread is a daemon thread. setDaemon ( ) :
Set the thread as a daemon thread prior its starting
execution.

More Related Content

Similar to oops with java modules i & ii.ppt

abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx upload
dashpayal697
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
manish kumar
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
Hitesh-Java
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Interface in java
Interface in javaInterface in java
Interface in java
Kavitha713564
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Interface
InterfaceInterface
Interface
vvpadhu
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
ssuser84e52e
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
talha ijaz
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
PawanMM
 

Similar to oops with java modules i & ii.ppt (20)

abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx upload
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
Interface in java
Interface in javaInterface in java
Interface in java
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Interface
InterfaceInterface
Interface
 
Interface
InterfaceInterface
Interface
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Java 06
Java 06Java 06
Java 06
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
 

More from rani marri

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
rani marri
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
rani marri
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
rani marri
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
rani marri
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri
 

More from rani marri (17)

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
 
must.pptx
must.pptxmust.pptx
must.pptx
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 

Recently uploaded

The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 

Recently uploaded (20)

The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 

oops with java modules i & ii.ppt

  • 1. Interface in Java An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve www.javatpoint.com/abstract-class-in-java There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple www.javatpoint.com/inheritance-in-java In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface. Why use Java interface? There are mainly three reasons to use interface. They are given below. o It is used to achieve abstraction. o By interface, we can support the functionality of multiple inheritance. o It can be used to achieve loose coupling. How to declare an interface? An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface. Syntax: 1. interface <interface_name>{ 2. 3. // declare constant fields 4. // declare methods that abstract 5. // by default. 6. } Internal addition by the compiler
  • 2. The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default, and the methods are public and abstract. + compiler-► interface Pnntable{ interface Pnntable{ nt M N=5 public static final int MIN=5 void print): public abstract void printn: Prints blejava Printable .class The relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface. class interface interface ik extends 4 1 implements ii extends class class interface Java Interface Example In this example, the Printable interface has only one method, and its implementation is provided in the A6 class. 1. interface printable{ 2. void print(); 3. } 4. class A6 implements printable{
  • 3. 5. public void print(){System.out.println(MHelloM);} 6. 7. public static void main(String args[]){ 8. A6 obj = new A6(); 9. obj.printO; 10. } 11. } Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance. 1. interface Printable{ 2. void print(); 3. } 4. interface Showable{ 5. void show(); 6. } 7. class A7 implements Printable,Showable{ 8. public void print(){System.out.println("Hello");} 9. public void show(){System.out.println(MWelcomeM);} 10. 11. public static void main(String args[]){ 12. A7 obj = new A7(); 13. obj.print();
  • 4. 14. obj.show(); 15. } 16. } Multiple inheritance is not supported through class in java, but it is possible by an interface As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of www.javatpoint.com/object-and-class-in-javabecause of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example: 1. interface Printable{ 2. void print(); 3. } 4. interface Showable{ 5. void print(); 6. } 7. 8. class TestInterface3 implements Printable, Showable{ 9. public void print(){System.out.println("Hello");} 10. public static void main(String args[]){ 11. TestInterface3 obj = new TestInterface3(); 12. obj.print(); 13. } 14. } Interface inheritance A class implements an interface, but one interface extends another interface. 1. interface Printable{ 2. void print(); 3. } 4. interface Showable extends Printable{ 5. void show(); 6. } 7. class TestInterface4 implements Showable{ 8. public void print(){System.out.println("Hello");} 9. public void show(){System.out.println("Welcome");} 10. 11. public static void main(String args[]){
  • 5. 12. TestInterface4 obj = new TestInterface4(); 13. obj.print(); 14. obj.show(); 15. } 16. }
  • 6. Object Oriented Programming in Java By Dr Rani Reddy
  • 7. Object Oriented Programming Concepts in Java Object oriented Programming is a paradigm or organizing principle for software, where the program is structured according to the information it manipulates, rather than the operations it does. Data, not procedures, shape the program.
  • 8. What is an Object ? An Object is defined as a software package that incorporates a set of related data and all the functions needed to manipulate this data. The related set of data, the data members, captures the state of an object.
  • 9. Defining Objects : STATE (Attributes) Encompasses all of the properties of an object. Each property has a value. All objects of the same type have same properties ( although they may have different values). Properties are implemented with Object Variables or instance variables .
  • 10. A motorcycle class might include the following attributes and have these typical values: • color : red, green, silver, brown • style : cruiser, sport bike, standard • Make : Honda, BMW, Bultaco Here color, style, make are the instance variables. Example :
  • 11. Defining Objects : BEHAVIOR Is how an object reacts, in terms of state changes and interaction with the other objects. Behavior is the only way objects can do anything to themselves or have anything done to them.
  • 12. A motorcycle class might have some behavior like: • Start the engine • Stop the engine • Speed up • Change gear • Stall Example :
  • 13. Defining Objects : BEHAVIOR The behavior is defined by the use of functions which are confined to a Class and are called member functions or Methods.
  • 14. Classes A class is a set of objects that share the same properties and behavior. Its where state and behavior of objects is defined through Variables and Methods. Example: Every Motorcycle is defined in the Motorcycle class.
  • 15. class Motorcycle { String make; String color; boolean enginestate = false; void startEngine() { if (enginestate = = true) Example of the Motorcycle Class
  • 16. System.out.println (“The engine is already on”) else { enginestate = true; System.out.println ( “The engine is now on”); } } }
  • 17. public static void main (String args[] ) { Motorcycle m = new Motorcycle(); m.make = “Yamaha RZ350”; m.color = “Yellow”; System.out.println(“Calling showAtts…”); m.showAtts(); The main() method for Motorcycle class
  • 18. System.out.println (“………………”); System.out.println(“Starting Engine …”); m.startEngine(); System.out.println (“………………”); System.out.println(“Calling showAtts…”); m.showAtts(); System.out.println (“………………”); System.out.println(“Starting Engine …”); m.startEngine(); }
  • 19. class Motorcycle { String make; String color; boolean enginestate = false; void startEngine() { if (enginestate = = true) System.out.println (“The engine is already on”) The final version of Motorcycle.java file
  • 20. else { enginestate = true; System.out.println ( “The engine is now on”); } } void showAtts () { System.out.println (“This motorcycle is a” +color+ “ ” +make);
  • 21. if (engineState = = true) System.out.println (“The engine is on.”); else System.out.println (“The engine is off.”); } public static void main (String args[] ) { Motorcycle m = new Motorcycle(); m.make = “Yamaha RZ350”; m.color = “Yellow”;
  • 22. System.out.println(“Calling showAtts…”); m.showAtts(); System.out.println (“………………”); System.out.println(“Starting Engine …”); m.startEngine(); System.out.println (“………………”); System.out.println(“Calling showAtts…”);
  • 24. The three major concepts in OOP are: • Encapsulation • Inheritance • Polymorphism
  • 25. Encapsulation Embedding both data and code into a single entity. •Allows us to use data hiding which is a way to prevent direct access to the variables in an object. • Separates the interface to the class from its implementation.
  • 26. Class Flight { int altitude; private int heading; int speed; float latitude; float longitude; // change the flight’s heading by angle degrees void turnFlight (int angle) { heading = (heading + angle) % 360; // make sure angle is in the range 0-359 degrees if (heading < 0) heading = heading + 360; }
  • 27. void setHeading (int angle) { heading = angle % 360; // make sure angle is in the range 0-359 degrees if (heading < 0) heading = heading + 360; } int getHeading( ) { return heading; } // print information about the flight void printFlight () { System.out.println(altitude + “ / ” + heading + “ / ” + speed); } }
  • 28.
  • 29. Inheritance Inheritance is the process by which one object acquires the properties of another object.
  • 30. Benefits of Inheritance •Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code (in the superclass) many times. • Programmers can implement superclasses called abstract classes that define “generic” behaviors. The abstract superclass defines and may partially implement the behavior but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.
  • 31. Example of Inheritance class CommercialFlight extends Flight { // extra members in CommercialFlight int flightNumber; int passengers; }
  • 32. The Commercial Flight Class inherits member variables and functions from Flight, and then adds its own member variables.
  • 33. Polymorphism Polymorphism is the ability of a single function name to be used to operate on many different types. It is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation.
  • 34. Polymorphism • We can deal with objects without the need to know what exact class they belong to. • This is an extension of the inheritance concept.
  • 35. JAVA - PACKAGES: What is package: Packages are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc. A package can be defined as a group of similar types of classes, interface, enumeration or sub-package. Using package it becomes easier to locate the related classes and it also provides a good structure for projects with hundreds of classes and other files. Benefits of using package in java: 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. 4) This packages can be provide reusability of code. 5) We can create our own package or extend already available package. Java Packages: Types: • Built-in Package: Existing Java package for example java.lang, java.util ,java.io etc. • User-defined-package: Java package created by user to categorize their project's classes and interface. How to Create a package: Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first statement in java source file. package mypackage; public class student { Statement; }
  • 36. The above statement will create a package name mypackage in the project directory. Java uses file system directories to store packages. For example the .java file for any class you define to be part of mypackage package must be stored in a directory called mypackage. Additional points about package: • A package is always defined as a separate folder having the same name as the package name. • Store all the classes in that package folder. • All classes of the package which we wish to access outside the package must be declared public. • All classes within the package must have the package statement as its first line. • All classes of the package must be compiled before use (So that they are error free) Example of Java packages: Package mypack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); } } How to compile Java packages: This is just like compiling a normal java program. If you are not using any IDE, you need to follow the steps given below to successfully compile your packages: 1. java -d directory javafilename For example javac -d . Simple.java The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot). How to run java package program: You need to use fully qualified name e.g. mypack.Simple etc to run the class. To Compile: javac -d . Simple.java To Run: java mypack.Simple Output: Welcome to package The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
  • 37. How to access package from another package: There are three ways to access the package from outside the package. 1. import package.*; 2. import package.classname; 3. fully qualified name. 1) Using packagename.*: If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. Example of package that import the packagename.*: //save by A.java package pack; public class A { public void msg() { System.out.println("Hello java");} } //save by B.java package mypack; import pack.*; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } } Output: Hello java 2) Using packagename.classname: If you import package.classname then only declared class of this package will be accessible. Example of package by import package.classname: //save by A.java package pack; public class A
  • 38. { public void msg() { System.out.println("Hello");} } //save by B.java package mypack; import pack.A; class B { public static void main(String args[]) { A obj = new A(); obj.msg(); } } Output: Hello 3) Using fully qualified name: If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. Example of package by import fully qualified name: //save by A.java package pack; public class A { public void msg() { System.out.println("Hello");} } //save by B.java package mypack; class B { public static void main(String args[]) { pack.A obj = new pack.A(); //using fully qualified name obj.msg(); }
  • 39. } Output: Hello Note: If you import a package, subpackages will not be imported. If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well. Subpackage in java: Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on. package com.javatpoint.core; class Simple{ public static void main(String args[]){ System.out.println("Hello subpackage"); } } To Compile: javac -d . Simple.java To Run: java com.javatpoint.core.Simple Output: Hello subpackage How to send the class file to another directory or drive: There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For example: //save as Simple.java package mypack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); }
  • 40. } To Compile: e:sources> javac -d c:classes Simple.java To Run: To run this program from e:source directory, you need to set classpath of the directory where the class file resides. e:sources> set classpath=c:classes;.; e:sources> java mypack.Simple Another way to run this program by -classpath switch of java: The -classpath switch can be used with javac and java tool. To run this program from e:source directory, you can use -classpath switch of java that tells where to look for class file. For example: e:sources> java -classpath c:classes mypack.Simple Output: Welcome to package
  • 41. Basics of a thread As with the Java concepts, everything about thread are defined in a class Thread. The Thread class encapsulates all of the control one will need over threads. The Thread class is our only link to manage how threads behave. In this Section, we will learn about : how to create and run a thread, the life cycle of a thread, and the thread controlling methods. Creating and Running a Thread There are two ways to define a thread: one is sub classing Thread and other is using the Runnable interface. Using the sub classing thread : With this method, we have to define a class as a sub class of the Thread class. This sub class should contain a body which will be defined by a method run(). This run() method contains the actual task that the thread should perform. An instance of this sub class is then to be created by a new statement, followed by a call to the thread's start() method to have the run() method executed. Let us consider the Illustration 6.1 which includes a program to create there individual threads that each print out their own " Hello World !" string. Illustration 6.1 // Creating and running threads using sub classing Thread // /* Creating three threads using the class Thread and then running them concurrently. */ class ThreadA extends Thread{ public void run( ) { for(int i = 1; i <= 5; i++) { System.out.println("From Thread A with i = "+ -1*i); } System.out.println("Exiting from Thread A ..."); } } class ThreadB extends Thread { public void run( ) { for(int j = 1; j <= 5; j++) { System.out.println("From Thread B with j= "+2* j); }
  • 42. System.out.println("Exiting from Thread B ..."); } } class ThreadC extends Thread{ public void run( ) { for(int k = 1; k <= 5; k++) { System.out.println("From Thread C with k = "+ (2*k-1)); } System.out.println("Exiting from Thread C ..."); } } public class Demonstration_111 { public static void main(String args[]) { ThreadA a = new ThreadA(); ThreadB b = new ThreadB(); ThreadC c = new ThreadC(); a. start(); b. start(); c. start(); System.out.println("... Multithreading is over "); } } OUTPUT: From Thread A with i = -1 From Thread A with i = -2 From Thread A with i = -3 From Thread B with j= 2 From Thread A with i = -4
  • 43. From Thread A with i = -5 Exiting from Thread A ... Multithreading is over From Thread C with k = 1 From Thread B with j= 4 From Thread B with j= 6 From Thread B with j= 8 From Thread B with j= 10 Exiting from Thread B ... From Thread C with k = 3 From Thread C with k = 5 From Thread C with k = 7 From Thread C with k = 9 Exiting from Thread C ... In the above simple example, three threads (all of them are of some type) will be executed concurrently. Note that a thread can be directed to start its body by start() method. Using the Runnable interface : A second way to create threads is to make use of the Runnable interface. With this approach, first we have to implement the Runnable interface.[Runnable interface is already defined in the system package java.lang with a single method run() as below : public interface Runnable { public abstract void run( ); } ] When we will create a new thread, actually a new object will be instantiated from this Runnable interface as the target of our thread, meaning that the thread will look for the code for the run( ) method within our object's class instead of inside the Thread's class. This is illustrated with an example where two processes Brother and Sister will be executed simultaneously. Illustration 6.2 /* Creating three threads using the Runnable interface and then running them concurrently. */
  • 44. class ThreadX implements Runnable{ public void run( ) { for(int i = 1; i <= 5; i++) { System.out.println("Thread X with i = "+ -1*i); } System.out.println("Exiting Thread X ..."); } } class ThreadY implements Runnable { public void run( ) { for(int j = 1; j <= 5; j++) { System.out.println("Thread Y with j = "+ 2*j); } System.out.println("Exiting Thread Y ..."); } } class ThreadZ implements Runnable{ public void run( ) { for(int k = 1; k <= 5; k++) { System.out.println("Thread Z with k = "+ (2*k- 1)); } System.out.println("Exiting Thread Z ..."); } } public class Demonstration_112 { public static void main(String args[]) { ThreadX x = new ThreadX(); Thread t1 = new Thread(x); ThreadY y = new ThreadY(); Thread t2 = new Thread(y);
  • 45. //ThreadZ z = new ThreadZ(); //Thread t3 = new Thread(z); Thread t3 = new Thread(new ThreadZ()); t1.start(); t2.start(); t3.start(); System.out.println("... Multithreading is over "); } } OUTPUT: Thread X with i = -1 Thread X with i = -2 Thread Z with k = 1 Thread Z with k = 3 Thread Z with k = 5 Thread Z with k = 7 Thread Z with k = 9 Exiting Thread Z ... ... Multithreading is over Thread Y with j = 2 Thread Y with j = 4 Thread Y with j = 6 Thread Y with j = 8 Thread Y with j = 10 Exiting Thread Y ...
  • 46. Thread X with i = -3 Thread X with i = -4 Thread X with i = -5 Exiting Thread X ... Note : Note in the above example, how after implementing objects, their thread is created and their threads start execution. Also note that, a class instance with the run( ) method defined within must be passed in as an argument in creating the thread instance so that when the start() method of this Thread instance is called, Java run time knows which run() method to execute. This alternative method of creating a thread is useful when the class defining run() method needs to be a sub class of other classes; the class can inherit all the data and methods of the super class. Life cycle of threads Each thread is always in one of five states, which is depicted in Figure 6.1 Figure 6.1 : Five states of a thread Newborn : When a thread is created (by new statement ) but not yet to run, it is called in Newborn state. In this state, the local data members are allocated and initialized. Runnable : The Runnable state means that a thread is ready to run and is awaiting for the control of the processor, or in other words, threads are in this state in a queue and wait their turns to be executed. Running : Running means that the thread has control of the processor, its code is currently being executed and thread will continue in this state until it get preempted by a higher priority thread, or until it relinquishes control. Blocked : A thread is Blocked means that it is being prevented from the Runnable ( or Running) state and is waiting for some event in order for it to reenter the scheduling queue. Dead : A thread is Dead when it finishes its execution or is stopped (killed) by another thread. Threads move from one state to another via a variety of means. The common methods for controlling a thread's state is shown in Figure 6.1. Below, we are to summarize these methods : start ( ) : A newborn thread with this method enter into Runnable state and Java run time create a system thread context and starts it running. This method for a thread object can be called once only stop( ) : This method causes a thread to stop immediately. This is often an abrupt way to end a thread. suspend( ) : This method is different from stop( ) method. It takes the thread and causes it to stop running and later on can be restored by calling it again. resume ( ) : This method is used to revive a suspended thread. There is no gurantee that the thread will start running right way, since there might be a higher priority thread running already, but, resume()causes the thread to become eligible for running. sleep (int n ) : This method causes the run time to put the current thread to sleep for n milliseconds. After n milliseconds have expired, this thread will become elligible to run again. yield( ) : The yield() method causes the run time to switch the context from the current thread to
  • 47. the next available runnable thread. This is one way to ensure that the threads at lower priority do not get started. Other methods like wait(), notify(), join() etc. will be discussed in subsequent discussion. Let us illustrate the use of these method in a simple Application. Illustration 6.3 /* Demonstration of thread class methods : getID() */ /* Java code for thread creation by extending the Thread class */ class ThreadId extends Thread { public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } } } public class Demonstration_113{ public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++) { ThreadId object = new ThreadId(); object.start(); }
  • 48. } } OUTPUT: Thread 21 Thread 22 Thread 23 Thread 25 Thread 26 Thread 27 Thread 24 Thread 28 s running s running s running s running s running s running s running s running Illustration 6.4 /* Demonstration of thread class methods : getID() */ /* Java code for thread creation by implementing the Runnable Interface */ class ThreadId implements Runnable { public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) {
  • 49. // Throwing an exception System.out.println ("Exception is caught"); } } } // Main Class class Demonstration_114 { public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++){ Thread object = new Thread(new ThreadId()); object.start(); } } } OUTPUT: Thread 21 Thread 23 Thread 24 Thread 25 Thread 22 Thread 27 Thread 26 Thread 28 s running s running s running s running s running s running s running s running
  • 50. Illustration 6.5 /* Use of yield(), stop() and sleep() methods */ class ClassA extends Thread{ public void run() { System.out.println("Start Thread A ...."); for(int i = 1; i <= 5; i++) { if (i==1) yield(); System.out.println("From Thread A: i = "+ i); } System.out.println("... Exit Thread A"); } } class ClassB extends Thread{ public void run() { System.out.println("Start Thread B ...."); for(int j = 1; j <= 5; j++) { System.out.println("From Thread B: j = "+ j); if (j==2) stop(); } System.out.println("... Exit Thread B"); } } class ClassC extends Thread{ public void run() { System.out.println("Start Thread C ...."); for(int k = 1; k <= 5; k++) { System.out.println("From Thread B: j = "+ k); if (k==3){ try{
  • 51. sleep(1000); }catch(Exception e){} } } System.out.println("... Exit Thread C"); } } public class Demonstration_115{ public static void main (String args[]) { ClassA t1 = new ClassA(); ClassB t2 = new ClassB(); ClassC t3 = new ClassC(); t1.start(); t2.start(); t3.start(); System.out.println("... End of executuion "); } }
  • 52. From Thread A: i = 3 From Thread A: i = 4 From Thread A: i = 5 ... Exit Thread A From Thread B: j = 2 From Thread B: j = 3 From Thread B: j = 4 From Thread B: j = 5 ... Exit Thread C Illustration 6.6 /* Use of suspend() and resume() methods */ class Thread1 extends Thread { public void run( ) { try{ System.out.println (" First thread starts running" ); sleep(10000); System.out.println (" First thread finishes running" ); } catch(Exception e){ } } } class Thread2 extends Thread { public void run( ) { try{ System.out.println ( "Second thread starts running"); System.out.println ( "Second thread is suspended itself "); suspend( );
  • 53. } System.out.println (" Second thread runs again" ); catch(Exception e){ } } } class Demonstration_116{ public staticvoid main (String args[ ] ){ try{ i.e. in Newborn state Thread1 first = new Thread1( ); // It is a newborn thread Thread2 second= new Thread2( ); // another new born thread first.start( ); // first is scheduled for running second.start( ); // second is scheduled for running is suspended System.out.println("Revive the second thread" ); // If it second.resume( ); " ); System.out.println ("Second thread went for 10 seconds sleep second.sleep (10000); running" ); System.out.println ("Wake up second thread and finishes System.out.println ( " Demonstration is finished "); } catch(Exception e){ } } }
  • 54. OUTPUT: Revive the second thread First thread starts running Second thread starts running Second thread is suspended itself Second thread went for 10 seconds sleep Status of a Thread It is some time essential to know some information about threads. There are number of methods defined in Thread which can be called for getting information about threads. Some of the most commonly used methods for thread's status are listed here : currentThread( ) : The CurrentThread() is a static method returns the Thread object which is the currently running thread. setName( String s) : The SetName() method is to assign a name s for a thread prior its execution. This, therefore, identifies the thread with a string name. This is helpful for debugging multi-threaded programs. getName( ) : This method returns the current string value of the thread's name as set by SetName(). setPriority (int p) : This method sets the thread's priotity to an integer value p passed in. There are several predefined priotiry constants defined in class Thread : MIN-PRIORITY, NORM- PRIORTY and MAX-PRIORITY, which are 1, 5, and 10 respectively. getPriority ( ) : This method returns the thread's current priority, a value between 1 and 10. isAlive ( ) : This method returns true if the thread is started but not dead yet. isDaemon ( ) : This method returns true if the thread is a daemon thread. Following is the Illustration 6.7 to give an idea how the above mentioned method may be utilized. Illustration 6.7 // Status information of threads // /* Setting priority to threads */ class ClassA extends Thread{ public void run() { System.out.println("Start Thread A ...."); for(int i = 1; i <= 5; i++) { System.out.println("From Thread A: i = "+ i); }
  • 55. System.out.println("... Exit Thread A"); } } class ClassB extends Thread{ public void run() { System.out.println("Start Thread B ...."); for(int j = 1; j <= 5; j++) { System.out.println("From Thread B: j = "+ j); } System.out.println("... Exit Thread B"); } } class ClassC extends Thread{ public void run() { System.out.println("Start Thread C ...."); for(int k = 1; k <= 5; k++) { System.out.println("From Thread B: j = "+ k); } System.out.println("... Exit Thread C"); } } class Demonstration_117{ public static void main (String args[]) { ThreadA t1 = new ThreadA(); ThreadB t2 = new ThreadB(); ThreadC t3 = new ThreadC(); t3.setPriority(Thread.MAX_PRIORITY); t2.setPriority(t2.getPriority() + 1);
  • 56. t1.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); t3.start(); System.out.println("... End of executuion "); } } OUTPUT: Start Thread A .... From Thread A: i = 1 From Thread A: i = 2 From Thread A: i = 3 From Thread A: i = 4 From Thread A: i = 5 ... Exit Thread A ... End of executuion Start Thread B .... Start Thread C .... From Thread B: j = 1 From Thread B: j = 2 From Thread B: j = 3 From Thread B: j = 4 From Thread B: j = 5 ... Exit Thread B From Thread B: j = 1 From Thread B: j = 2 From Thread B: j = 3 From Thread B: j = 4 From Thread B: j = 5
  • 57. ... Exit Thread C Illustration 6.8 /* Data race example. */ public class Demonstration_118 extends Thread { public static int x; public void run() { for (int i = 0; i < 100; i++) { x = x + 1; } x = x - 1; } } public static void main(String[] args) { x = 0; for (int i = 0; i < 1000; i++){ new Demonstration_118().start(); System.out.println(x); } } // x not always 0! Synchronization and Inter-Thread Communication It is already mentioned that threads in Java are running in the same memory space, and hence it is easy to communicate between two threads. Inter-thread communications allow threads to talk to or wait on each other. Again, because all the threads in a program share the same memory space, it is possible for two threads to access the same variables and methods in object. Problems may occur when two or more threads are accessing the same data concurrently, for example, one thread stores data into the shared object and the other threads reads data, there can be synchronization problem if the first thread has not finished storing the data before the second one goes to read it. So we need to take care to access the data by only one thread process at a time. Java provides unique language level support for such
  • 58. synchronization. in this Section we will learn how synchronization mechanism and inter-thread communications are possible in Java. Synchronization To solve the critical section problem, one usual concept is known what is called monitor. A monitor is an object which is used as a mutually exclusive lock ( called mutex). Only one thread may own a monitor at a given time. When a thread acquires a lock it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the owner thread exits the monitor. But in Java, there is no such monitor. In fact, all Java object have their own implicit monitor associated with them. Here, the key word synchronized is used by which method (s) or block of statements can be made protected from the simultaneous access. With this, when a class is designed with threads in mind, the class designer decides which methods should not be allowed to execute concurrently. when a class with synchronized method is instantiated, the new object is given its own implicit monitor. The entire time that a thread is inside of a synchronized method, all other threads that try to call any other synchronized method on the same instance have to wait. In order to exit the monitor and relinquish control of the object to the next waiting thread the monitor owner simply needs to return from the method. Let us illustrate this mechanism with a simple example. Suppose, we want to maintain a bank account of customers. Several transactions, such as deposite some amount to an account and withdraw some amount from an account etc. are possible. Now, for a given account, if two or more transactions come simultaneously then only one transaction should be allowed at a time instead of simulataneous transaction processing so that data inconsistency will never occur. So, what we need is to synchronize the transaction. Illustration 6.9 is to implement such a task. Illustration 6.9 /* The following Java application shows how the transactions in a bank can be carried out concurrently. */ class Account { public int balance; public int accountNo; void displayBalance() { System.out.println("Account No:" + accountNo + "Balance: " + balance); } synchronized void deposit(int amount){ balance = balance + amount;
  • 59. System.out.println( amount + " is deposited"); displayBalance(); } synchronized void withdraw(int amount){ balance = balance - amount; System.out.println( amount + " is withdrawn"); displayBalance(); } } class TransactionDeposit implements Runnable{ int amount; Account accountX; TransactionDeposit(Account x, int amount){ accountX = x; this.amount = amount; new Thread(this).start(); } } public void run(){ accountX.deposit(amount); } class TransactionWithdraw implements Runnable{ int amount; Account accountY; TransactionWithdraw(Account y, int amount) { accountY = y; this.amount = amount; new Thread(this).start();
  • 60. } public void run(){ accountY.withdraw(amount); } } class Demonstration_119{ public static void main(String args[]) { Account ABC = new Account(); ABC.balance = 1000; ABC.accountNo = 111; TransactionDeposit t1; TransactionWithdraw t2; t1 = new TransactionDeposit(ABC, 500); t2 = new TransactionWithdraw(ABC,900); } } In the above example, the keyword synchronized is used for the methods void deposite(..) and void withdraw(^) so that these two methods will never run for the same object instance simultaneously.
  • 61. Alternatively, if one wants to design a class that was not designed for multi-thread access and thus has non-synchronized methods, then it can be wrapped the call to the methods in a synchronized block. Here is the general form of the synchronized statement : synchronized (Object ) { block of statement(s) } where Object is any object reference. For example, make all the methods in Account class as non-synchronized (remove the synchronized key word). Then modify the code for run( ) in class TransactionDeposite and class TransactionWithdraw are as under : public void run( ) { // in TransactionDeposite synchronized (accountX ) { accountX.deposite(amount ); } } public void run( ) { // synchronized (accountY ) { accountY.withdraw(amount in TransactionWithdraw ); } } You will get the same output. Interested reader may try to run the program without using synchronization and observe the result. Note: In a class, non-synchronized methods are concurrently executable. Inter-thread Communication There are three ways for threads to communicate with each other. The first is through commonly shared data. All the threads in the same program share the same memory space. If an object is accessible to various threads then these threads share access to that object's data member and thus communicate each other. The second way for threads to communicate is by using thread control methods. There are such three methods by which threads communicate for each other : suspend ( ): A thread can suspend itself and wait till other thread resume it. resume ( ): A thread can wake up other waiting thread (which is waiting using suspend() ) through its resume() method and then can run concurrently. join ( ) :This method can be used for the caller thread to wait for the completion of called thread. The third way for threads to communicate is the use of three methods; wait(), notify(), and notifyAll(); these are defined in class Object of package java.lang. Actually these three
  • 62. methods provide an elegant inter-process communication mechanism to take care the deadlock situation in Java. As there is multi-threading in program, deadlock may occur when a thread holding the key to monitor is suspended or waiting for another thread's completion. If the other thread is waiting for needs to get into the same monitor, both threads will be waiting for ever. The uses of these three methods are briefed as below : wait ( ):This method tells the calling thread to give up the monitor and make the calling thread wait until either a time out occurs or another thread call the same thread's notify() or notifyAll() method. Notify ( ): This method wakes up the only one (first) waiting thread called wait() on the same object. notifyAll( ): This method will wake up all the threads that have been called wait( ) on the same object. Now, let us demonstrate the classical use of these methods. Illustration 6.6 is for this purpose. Illustration 6.10 : // Inter thread communication : Producer & Consumer problem // class Q { processes // Q is a class containing two parallel int n; boolean flag = false; //PRODUCER synchronized void put( int n) { // Produce a value if(flag) { try wait( ); catch(InterruptedException e); // to the } // critical section this.n = n; System.out.println( "Produce :" + n); // Critical Section flag = true; // Exit from the notify( ); // Entr // crit } //CONSUMER
  • 63. started synchronized int get( ) { // Consume a value if(! flag) { // Entry try wait( ); catch(InterruptedException e); // to the } // critical section System.out.println( "Consume :" + n); // Critical Section flag = false; // Exit from the notify( ); return( n ); } // crit class Producer implement Runnable { Q q; Producer ( Q q ) { this.q =q; new thread (this).start ( ) ; // Thread for Producer process // constructor // Producer process is } public void run( ) { // infinite running thread for Producer int i = 0; while (true ) q.put ( i++ ); } } class Consumer implement Runnable { // Thread for consumer process Q q;
  • 64. Consumer (Q q ) { // Constructor this.q = q; new Thread (this).start ( ); } public void run( ) { // infinite running thread for Consumer while (true) q.get ( ); } } class PandC { public static void main( String args[ ] ) { Q q = new Q( ); // an instance of parallel processes is created producer new Producer(q) ; new Consumer (q); // Run the thread for // Run consumer thread } } To understand this critical section problem in operating system design, user may be referred to : Operating system concept by Peterson and Sylberchotze, Addiction Wesley Inc. Note : All three methods i.e. wait(), notify(), and notifyAll() must only be called from the inside of synchronized methods. Thread Groups and Daemon There are two other variation in thread class known : ThreadGroup and Daemon. ThreadGroup, as its name implies, is a group of threads. A thread group can have both threads and other thread groups as its member elements. In Java, there is a default thread group called SystemThreadGroup, which is nothing but the Java run time itself. When a Java application is started, the Java run time creates the main thread group as a member of the system thread group. A main thread is created in the main thread group to run the main( ) method of the Application. In fact, every thread instance is member of exactly one thread group. By default, all new user created threads and thread groups) will become the members of the main thread
  • 65. group. All the threads and thread in an application form a tree with the system thread group as the root. Daemon threads are service threads. They exist to provide service threads. They exist to provide services to other threads. They normally run in an infinite loop and attending the client threads requesting services. When no other threads exist daemon thread is automatically ceased to exist. A new thread group can be created by instantiating the thread group class. For example, Threadgroup TG = new ThreadGroup ( ) ; Thread T = new Thread ( TG) ; These two statements creates a new thread group TG which contains a thread T as the only member. To create a daemon thread, there is a method setDaemon() can be called just after the creation of a thread and before the execution is started. For example, following two statement is to make a thread as demon thread. Thread T = new Thread ( ) ; T setDaemon (true); The constructor of the thread is a good candidate for making this method call, Also, by default, all the threads created by a daemon thread are also daemon thread. Some commonly used methods for handling thread groups and daemon are listed below : getName ( ) :Returns the name of the thread group . setName ( ) :Sets the name of the thread group . geParent ( ) :Returns the parent thread group of the thread group . getMaxPriority :Returns the current maximum priority of the thread group. activeCount ( ) :Returns the number of active threads in the thread group. activeGroupCount :Returns the number of active threads groups in the thread group. isDaemon ( ) :Returns true if the thread is a daemon thread. setDaemon ( ) : Set the thread as a daemon thread prior its starting execution.