0% found this document useful (0 votes)
28 views

Unit 3

Uploaded by

preetippalankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Unit 3

Uploaded by

preetippalankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

Unit – 3

Interfaces, Packages and Multithreaded Programming

Chapter 1– Interfaces: Multiple Inheritance

Chapter 2– Packages: Putting Classes Together

Chapter 3 – Multithreaded Programming


Chapter 1
Interfaces: Multiple Inheritance
Topics
• Introduction
• Defining Interfaces
• Extending Interfaces
• Implementing Interfaces
• Accessing Interface Variables
Introduction
What Is Multiple Inheritance?
-- Child class will inherit properties from two or more
parent class.

Why Multiple Inheritance is not there in java?


The reason behind this is to prevent ambiguity.
Consider a case where class B extends class A and
Class C and both class A and C have the same method
display().
Now java compiler cannot decide, which display
method it should inherit. To prevent such situation,
multiple inheritances is not allowed in java.
Java does not support multiple inheritance. That is
classes in Java cannot have more than one super class.
class A extends B extends C
{ ………………
………………..
}
The above definition is not permitted in java.
• Java provides an alternate approach known as
interfaces to support the concept of multiple
inheritance.
• Although a Java class cannot be a subclass of more
than one superclass, it can implement more than one
interface, thereby enabling us to create classes that
build upon other classes without the problems
Defining Interfaces
• An interface is basically a kind of class
• Like classes, interfaces contain methods and variables but
with a major difference.
• The difference is that interfaces define only abstract
methods and final fields.
• This means that interfaces do not specify any code to
implement these methods and data fields contain only
constants.
• Therefore, it is the responsibility of the class that
implements an interface to define the code for
implementation of these methods.
• An interface is very similar to that for defining a
class.
• The general form of an interface definition is:

interface InterfaceName
{
variables declaration;
methods declaration;
}

• Here, interface is the key word and InterfaceName


is any valid Java variable (just like class names)
• Variables are declared as follows:

static final type VariableName = Value;

• All variables are declared as constants.


• Methods declaration will contain only a list of
methods without any body statements.

return-type methodNamel (parameter_list);


Ex 1:
interface Item
{
static final int code = 1001;
static final String name = "Fan";
void display ();
}

• The code for the method is not included in the interface and the
method declaration simply ends with a semicolon.
• The class that implements this interface must define the code
for the method.
Ex:2 interface Area
{
final static float pi 3.142F;
float compute (float x, float y);
void show ();
}
Difference between class & Interface

Class Interface
1. The members of an interface are
1. The members of a class can
always declared as constant,i.e.,
be constant or variables. their values are final.

2. The class definition can 2. The methods in an interface are


contain the code for each of abstract in nature, i.e., there is
its methods. That is, the no code associated with them. It
methods can be abstract or is later defined by the class that
non-abstract. implements the interface.

3. It cannot be used to declare


3. It can be instantiated by objects. It can only be inherited
declaring objects. by a class.

4. It can only use the public access


4. It can use various access
specifier.
specifiers like It can only us
public, private, or protected.
Extending Interfaces
• Like classes, interfaces can also be extended. That is,
an interface can be subinterfaced from other
interfaces.
• The new subinterface will inherit all the members
of the superinterface which is similar to subclasses.
• This is achieved using the keyword extends as
shown below:
interface name2 extends name1
{
body of name2;
}
Ex: interface ItemConstants
{
int code = 1001;
String name = "Fan";
}
interface Item extends ItemConstants
{
void display ();
}

• We can put all the constants in one interface and the


methods in the other.
• This will enable us to use the constants in classes where the
methods are not required.
• The interface Item would inherit both the
constants code and name into it.
• Note that the variables name and code are
declared like simple variables.
• It is allowed because all the variables in an
interface are treated as constants although
the keywords final and static are not present.
• We can also combine several interfaces together into a single
interface.
Ex: interface ItemConstants
{
int code = 1001;
String name = "Fan";
}
interface ItemMethods
{
void display();
}
interface Item extends ItemConstants, ItemMethods
{
……………………………
…………………………..
}
• interfaces are allowed to extend to other
interfaces, subinterfaces cannot define the
methods declared in the superinterfaces.
• After all, subinterfaces are still interfaces, not
classes.
• Instead, it is the responsibility of any class that
implements the derived interface to define all the
methods.
• Note that when an interface extends two or more
interfaces, they are separated by commas.
• An interface cannot extend classes. This would
violate the rule that an interface can have only
abstract methods and constants.
IMPLEMENTING INTERFACES
• Interfaces are used as "superclasses" whose
properties are inherited by classes.
• It is therefore necessary to create a class that
inherits the given interface.
• This is done as follows:

class classname implements interfacename


{
body of classname
}
class classname extends superclass
implements interface1, interface2,……
{
body of classname
}

This shows that a class can extend another class


while implementing interfaces
interface Area // Interface defined
{
final static float pi= 3.14F;
float compute (float x, float y);
}
class Rectangle implements Area //Interface Implementation
{
public float compute(float x,float y)
{
return(x*y);
}
}
class Circle implements Area //Another implementation
{
public float compute (float x, float y)
{
return(pi*x*x);
}
}
class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area; // Interface object
area = rect;
System.out.println("Area of Rectangle = "+ area.compute (10, 20));
area = cir;
System.out.println("Area of Circle = "+ area.compute(10,0));
• To implement the methods, we need to refer
to the class objects as types of the interface
rather than types of their respective classes.
• If a class that implements an interface does
not implement all the methods of the
interface, then the class becomes an abstract
class and cannot be instantiated.
Accessing Interface Variables
• Interfaces can be used to declare a set of constants that
can be used in different classes
• This is similar to creating header files in C++ to contain
a large number of constants.
• Since such interfaces do not contain methods, there is
no need to worry about implementing any methods.
• The constant values will be available to any class that
implements the interface.
• The values can be used in any method, as part of any
variable declaration, or anywhere where we can use a
final value,
Ex:
interface A
{
int m = 10;
int n = 50;
}
class B implements Ai
{ int x = m;
void methodB (int size)
{
…………….
if (size < n)
}
}
Java Program to implement multiple inheritance
using interface
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber()
{
System.out.println("Roll No : " +
rollNumber);
}
}
class Test extends Student
{
float part1, part2;
void getMarks(float m1, float m2)
{
part1 = m1;
part2 = m2;
}
void putMarks()
{
System.out.println("Marks obtained ");
System.out.println("Part 1 = " + part1);
System.out.println("Part 2 = " + part2);
}
}
interface Sports
{
float sportWt = 6.0f;
void putwt();
}
class Results extends Test implements Sports
{
float total;
public void putwt()
{
System.out.println("Sports Wt = "+ sportWt);
}
void display()
{
total = part1 + part2 + sportWt;
putNumber();
putMarks();
putwt();
System.out.println("Total score = "+ total);
}
class ImplementInterface
{
public static void main(String args[])
{
Results s1 = new Results();
s1.getNumber(1234);
s1.getMarks(27.5F,33.0F);
s1.display();
}
}
Chapter 2
Packages: Putting Classes Together
Topics
• Introduction
• Java API Packages
• Using System Packages
• Naming Conventions
• Creating Packages
• Accessing a Package
• Using a Package
• Adding a Class to a Package
• Hiding Classes
Introduction
• one of the main features of OOP is its ability to
reuse the code already created.
• One way of achieving this is by extending the
classes and implementing the interfaces.
• This is limited to reusing the classes within a
program.
• What if we need to use classes from other
programs without physically copying them into the
program?
This can be accomplished in Java by using
packages, a concept similar to "class libraries" in
• Packages are Java's way of grouping a variety of classes
and/or interfaces together.
• The grouping is usually done according to functionality.
• Packages act as "containers" for classes.
• By organizing our classes into packages we achieve the
following benefits:
1. The classes contained in the packages of other
programs can be easily reused.
2. In packages, classes can be unique compared with
classes in other packages.
That is, two classes in two different packages can
have the same name.
They may be referred by their fully qualifiedname,
comprising the package name and the class name.
3. Packages provide a way to "hide" classes thus
preventing other programs or packages from
accessing classes that are meant for internal
use only.
4. Packages also provide a way for separating
"design" from "coding“.
First we can design classes and decide
their relationships, and then we can implement
the Java code needed for the methods.
It is possible to change the
implementation of any method without
affecting the rest of the design.
• For most applications need to use different
sets of classes, one for the internal
representation of our program's data, and the
other for external presentation purposes.
• Build our own classes for handling our data
and use existing class libraries for designing
user interfaces.
• Java packages are therefore classified into two
types.
– The first category is known as Java API packages
and
– the second is known as user defined packages.
Java API Packages
• Java API provides a large number of classes
grouped into different packages according to
functionality.

Frequently used API packages


Java System Packages and their classes
Package Contents
name
java.lang Language support classes. These are
classes that Java compiler itself uses and
therefore they are automatically imported.
They include classes for primitive types,
strings, math functions, threads and
exception.
java.util Language utility classes such as vectors,
hash tables, random numbers, date, etc.
java.io Input/output support classes. They provide
facilities for the input and output of data.
Package Contents
name

java.awt Set of classes for implementing graphical


user interface. They include classes for
windows, buttons, lists, menus and so on.

java.net Classes for networking. They include


classes for communicating with local
computers as well as with internet
servers.
java.applet Classes for creating and implementing
applets.
Using System Packages
• The packages are organised in a hierarchical structure as shown in
fig.
• This shows that the package named java contains the package awt,
which in turn contains various classes required for implementing
graphical user interface.
 There are two ways of accessing the classes stored
in a package.
 The first approach is to use the fully qualified class
name of the class that need to be used.
 This is done by using the package name containing the
class and then appending the class name to it using the
dot operator.
Ex: java.awt.Color;

 awt is a package within the package java and the


hierarchy is represented by separating the levels with
dots. class Color is in the awt package.
 Its Best when need to access the class only once or when
we need not have to access any other classes of the
package.
• Second approach is that in some cases need
to use a class in a number of places in the
program or we may like to use many of the
classes contained in a package.
import packagename.classname;
Or
import packagename.*;

• These are known as import statements and


must appear at the top of the file, before any
class declarations, import is a keyword.
• The first statement allows the specified class in the
specified package to be imported
Ex: import java.awt.Color;
• imports the class Colour and therefore the class
name can be directly used in the program.
• There is no need to use the package name to
qualify the class.

• The second statement imports every class


contained in the specified package.
For ex: import java.awt.*;
• It will bring all classes of java.awt package.
Naming Conventions
• Packages can be named using the standard Java naming rules.
• By convention packages begin with lowercase letters.
• This makes it easy for users to distinguish package names from
class names
• all class names, again by convention, begin with an uppercase
letter. Method names begin with lowercase letter.
• For ex:
double y = java.lang.Math.sqrt(x);

package class method


• This statement uses a fully qualified class name Math to invoke
the method sqrt().
• For ex: java.awt.Point pts[ ];
• The above statement declares an array of Point type
objects using the fully qualified class name.
• Every package name must be unique to make the best
use of packages.
• Duplicate names will cause run-time errors. Since
multiple users work on Internet, duplicate package
names are unavoidable.
• Java designers have recognized this problem and
therefore suggested a package naming convention
that ensures uniqueness.
• This suggests the use of domain names as prefix to
the preferred package names.
Ex: cbe.psg.mypackage;
• Here cbe denotes city name and psg denotes
organisation name
• we can create a hierarchy of packages within
packages by separating levels with dots.
Creating Packages
• To create our own packages first declare the
name of the package using the package
keyword followed by a package name.
• This must be the first statement in a Java
source file.
• Then define a class, just as we normally define
a class.
• Ex: package firstpackage;
public class Firstclass
{ ……………….
………………..(body of class)
}
• The package name is firstPackage.
• The class First Class is considered as a part of this package.
• This would be saved as a file called FirstClass.java, and located
in a directory named firstPackage.
• When the source file is compiled, Java will create a .class file
and store it in the same directory.
• Remember that the .class files must be located in a directory
that has the same name as the package, and this directory should
be a subdirectory of the directory where classes that will import
the package are located.
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the
form:
package packagename;
2. Define the class that is to be put in the package and
declare it public.
3. Create a subdirectory under the directory where the main
source files are stored.
4. Store the listing as the classname.java file in the
subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.

Remember that case is significant and therefore the


subdirectory name must match the package name exactly.
• Java supports the concept of package
hierarchy. This is done by specifying multiple
names in a package statement, separated by
dots
• Example: package first
Package.secondPackage;
• This approach allows to group related classes
into a package and then group related
packages into a larger package.
• Remember to store this package in a
subdirectory named firstPackage/second
Package.
• A java package file can have more than one
class definitions. In such cases, only one of the
classes may be declared public and that class
name with .java extension is the source file
name.
• When a source file with more than one class
definition is compiled, Java creates
independent .class files for those classes.
Accessing a package
• Java system package can be accessed either
using a fully qualified class name or using the
import statement.
• import statements are used when there are
many references to a particular package or the
package name is too long
• The same approaches can be used to access
the user-defined packages as well.
• The general form of import statement for
searching a class is as follows:
import package1 [.package2] [.package3].classname;

• Here package1 is the name of the top level


package, package2 is the name of the package
that is inside the packagel, and so on.
• We can have any number of packages in a
package hierarchy. Finally, the explicit classname
is specified.Note that the statement must end
with a semicolon (;).
• The import statement should appear before any
class definitions in a source file.
• Multiple import statements are allowed. The following is
an example of importing a particular classs
• import firstPackage.secondPackage.MyClass;
• After defining this statement, all the members of the
class MyClass can be directly accessed using the class
name or its objects directly without using the package
name.
• Another approach to access :
import packagename.*;
• Here, packagename may denote a single package or a
hierarchy of packages
• The star (*) indicates that the compiler should search
this entire package hierarchy when it encounters a class
name. This implies that we can access all classes
contained in the above package directly
• The major drawback of the shortcut approach
is that it is difficult to determine from which
package particular member came.
• But the advantage is that we need not have to
use long package names repeatedly in the
program.
Using a Package
• A package named pkg1 containing a single class ClassA.
Ex: package pkg1;
public class ClassA
{
public void displayA()
{
System.out.println("Class A");
}
}
• This source file should be named ClassA.java and stored in
the subdirectory pkg1.
• Now compile this java file. The resultant ClassA.class will be
stored in the same subdirectory.
import pkg.ClassA;
class ClassB
{
public static void main(String args[])
{
ClassA obj=new ClassA();
obj.displayA();
}
}
• A program that imports the class ClassA from the package pkg1.
• The source file should be saved as classB.java and then
compiled. The source file and the compiled file should be saved
in the main directory.
• Run the program and obtain the results.
Chapter 3
Multithreaded Programming
Topics
• Introduction
• Creating Threads
• Extending the Thread Class
• Stopping and Blocking a Thread
• Life Cycle of a Thread
• Using Thread Methods
• Thread Exceptions
• Thread Priority
• Synchronization
• Implementing the 'Runnable‘ Interface
Introduction

• The operating systems can execute several


programs simultaneously. This ability is known
as multitasking.

• In system's terminology, it is called


multithreading.
• Multithreading is a conceptual programming
paradigm where a program (process) is
divided into two or more subprograms
(processes), which can be implemented at the
same time in parallel.
• For ex: one subprogram can display an
animation on the screen while another may
build the next animation to be displayed.
• This is something similar to dividing a task
into subtasks and assigning them to different
people for execution independently and
simultaneously.
• Java programs contain only a single sequential
flow of control, when we execute a normal
program.
• The program begins, runs through a sequence
of executions, and finally ends.
• At any given point of time, there is only one
statement under execution
• A thread is similar to a program that has a
single flow of control. It has a beginning, a
body, and an end, and executes commands
sequentially.
• Then all main programs can be called single-
threaded programs. Every program will have
at least one thread.
• A unique property of Java is its support for
multithreading.
• Java allows to use multiple flows of control in
developing programs.
• Each flow of control may be thought of as a
separate tiny program (or module) known as a
thread that runs in parallel.
• A program that contains multiple flows of
control is known as multithreaded program.
• Fig shows that Java program with four threads, one
main and three others. The main thread is actually
the main method module, which is designed to
create and start the other three threads, namely A,
B and C.
• Once initiated by the main thread, the threads A,
B, and C run concurrently and share the resources
jointly.
• The ability of a language to support multithreads is
referred to as concurrency.
• Since threads in Java are subprograms of a main
application program & share the same memory
space, they are known as lightweight threads or
lightweight processes
• Threads running in parallel does not really
mean that they actually run at the same time.
• Since all the threads are running on a single
processor, the flow of execution is shared
between the threads.
• The Java interpreter handles the switching of
control between the threads in such a way
that it appears they are running concurrently.
• Multithreading is useful in a number of ways.
It enables programmers to do multiple things
at one time. They can divide a long program
into threads and execute them in parallel.
• For example, we can send tasks such as
printing into the background and continue to
perform some other task in the foreground.
• This approach would considerably improve
the speed of our programs.
Difference Between Multithreading & Multitasking
Multithreading Multitasking
1) It is a programming concept in which a 1) It is an operating system concept in
program or a process is divided into two which multiple tasks are performed
or more subprograms or threads that are simultaneously.
executed at the same time in parallel.

2) It supports execution of multiple parts 2) It supports execution of multiple


of a single program simultaneously. programs simultaneously.
3) The processor has to switch between 3) The processor has to switch between
different parts or threads of a program. different programs or processes.
4) It is highly efficient. 4) It is less efficient in comparison to
multithreading.
5) A thread is the smallest unit in 5) A program or process is the smallest
multithreading. unit in a multitasking environment.
6) It helps in developing efficient 6) It helps in developing efficient
programs. operating systems.
7) It is cost-effective in case of context 7) It is expensive in case of context
switching. switching.
Creating Threads
• Creating threads in Java is simple. Threads are
implemented in the form of objects that contain a
method called run().
• The run() method is the heart and soul of any
thread. It makes up the entire body of a thread
and is the only method in which the thread's
behavior can be implemented.
public void run()
{ …………..
…………..(statements for implementing thread)
}
• The run() method should be invoked by an object of the
concerned thread. This can be achieved by creating the
thread and initiating it with the help of another thread
method called start ().

• A new thread can be created in two ways.


1. By creating a thread class:
Define a class that extends Thread class and override
its run() method with the code required by the thread.

2. By converting a class to a thread:


Define a class that implements Runnable interface.
The Runnable interface has only one method run(), that is
to be defined in the method with the code to be executed
by the thread.
• The approach to be used depends on what the
class we are creating requires.
• If it requires to extend another class, then we
have no choice but to implement the
Runnable interface, since Java classes cannot
have two superclasses.
Extending The Thread Class
• To make class runnable as thread by extending the
class java.lang.Thread.
• This gives us access to all the thread methods
directly.

• It includes the following steps:


1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible
for executing the sequence of code that the thread
will execute.
3. Create a thread object and call the start() method
to initiate the thread execution.
Declaring the class
• The Thread class can be extended as follows:

class MyThread extends Thread


{ …………………..
…………………..
}
A new type of thread MyThread is created.
Implementing the run() Method
• The run() method has been inherited by the class
MyThread.
• Override this method in order to implement the code to
be executed by our thread.
• The basic implementation of run():
public void run()
{ ……………………
………………….. //Thread code here
}
When we start the new thread, Java calls the thread's run()
method, so it is the run() where all the action takes place.
 Starting New Thread
• To create and run an instance of our thread class:
MyThread aThread = new MyThread();
aThread.start(); // invokes run() method

• The first line instantiates a new object of class MyThread.


• The statement just creates the object. The thread that will
run this object is not yet running. The thread is in a
newborn state.
• The second line calls the start() method causing the thread
to move into the runnable state.
• Then, the Java runtime will schedule the thread to run by
invoking its run() method. Now, the thread is said to be in
the running state.
An example of using the Thread Class
import java.lang.Thread;
class Hi extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Hi");
//try{Thread.sleep(1000);}catch(Exception e)
{}
}
}
class Hello extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Hello");
//try{Thread.sleep(2000);}catch(Exception e){}
}
}
}
public class ThreadEx
{
public static void main(String args[])
{
//Hi obj1=new Hi();
//Hello obj2=new Hello();
new Hi().start();
new Hello().start();
}
}
Creating threads using the thread class
class A extends Thread
{
public void run()
{
for (int i=1; i<=5; i++)
{
System.out.println("\t From ThreadA : i = " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for (int j=1; j<=5; j++)
{
System.out.println("\tFrom Thread B :j = "+ j);
}
System. out. println("Exit from B ");
class C extends Thread
{
public void run()
{
for (int k=1; k<=5; k++)
{
System.out.println("\t From Thread C: k = " + k);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
• The program creates three threads A, B, and C
for undertaking three different tasks.
• The main method in the ThreadTest class is
known as "main thread".
• The main thread dies at the end of its main
method, before it dies, it creates and starts all
the three threads A, B, and C.
• Compact way of starting thread
new A().start();
• Equivalent to
A obj =new A();
obj.start();

• Immediately after the thread A is started, there will


be two threads running in the program:
the main thread and
the thread A.
• The start() method returns back to the main thread
immediately after invoking the run() method, thus
allowing the main thread to start the thread B.
• There are total four separate threads running
in parallel.
• They are running concurrently on their own.
They do not follow any specific order.
• They are running independently of one
another and each executes whenever it has a
chance.
Stopping and Blocking a Thread
Stopping a Thread
• To stop a thread from running further, call its
stop() method,
obj.stop();
• This statement causes the thread to move to the
dead state.
• A thread will also move to the dead state
automatically when it reaches the end of its
method.
• The stop() method may be used when the
premature death of a thread is desired.
Blocking a Thread
• A thread can also be temporarily suspended or blocked
from entering into the runnable and subsequently running
state by using either of the following thread methods:
sleep() //blocked for a specified time
suspend() //blocked until further orders
wait() //blocked until certain conditions occur

• These methods cause the thread to go into the blocked (or


not-runnable) state.
• The thread will return to the runnable state when the
specified time is elapsed in the case of sleep(),
• the resume() method is invoked in the case of suspend(), and
• the notify() method is called in the case of wait().
Life Cycle Of A Thread (Imp***)
• During the life time of a thread, there are many states
it can enter. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

• A thread is always in one of these five states. It can


move from one state to another via a variety of ways
as shown in fig.
State transition diagram of a thread
1) Newborn State
• When we create a thread object, the thread is
born and is said to be in newborn state.
• The thread is not yet scheduled for running.
• At this state, we can do only one of the
following things with it:
– Schedule it for running using start() method
– Kill it using stop() method.
• If scheduled, it moves to the runnable state as
shown in below fig.
• If we attempt to use any other method at this
stage, an exception will be thrown.
2) Runnable State
• The runnable state means that the thread is ready
for execution and is waiting for the availability of
the processor.
• That is, the thread has joined the queue of threads
that are waiting for execution.
• If all threads have equal priority, then they are
given time slots for execution in round robin
fashion, i.e., first-come, first-serve manner.
• The thread that relinquish(give up) control joins
the queue at the end and again waits for its turn.
• This process of assigning time to threads is known
as time-slicing.
• If we want a thread to relinquish control to
another thread to equal priority before its
turn comes, its done using yield() method.
3) Running State
• Running means that the processor has given
its time to the thread for its execution.
• The thread runs until it relinquishes control on
its own or it is preempted(acquire) by a higher
priority thread.
• A running thread may relinquish its control in one of
the following situations.
1. It has been suspended using suspend() method.
A suspended thread can be revived by using the
resume() method.
This approach is useful when we want to suspend a
thread for some time due to certain reason, but do
not want to kill it.
2. It has been made to sleep.
 We can put a thread to sleep for a specified time period
using the method sleep(time) where time is in
milliseconds.
 This means that the thread is out of the queue during
this time period.
 The thread re-enters the runnable state as soon as this
time period is elapsed.
3. It has been told to wait until some event occurs.
This is done using the wait() method. The thread can
be scheduled to run again using the notify() method.
4) Blocked State
• A thread is said to be blocked when it is prevented
from entering into the runnable state and
subsequently the running state.
• This happens when the thread is suspended,
sleeping, or waiting in order to satisfy certain
requirements.
• A blocked thread is considered "not runnable" but
not dead and therefore fully qualified to run again.
5) Dead State
• Every thread has a life cycle. A running thread
ends its life when it has completed executing
its run() method. It is a natural death.
• We can kill it by sending the stop message to it
at any state thus causing a premature death to
it.
• A thread can be killed as soon it is born, or
while it is running, or even when it is in "not
runnable" (blocked) condition.
 Using Thread Methods

• Thread class methods can be used to control


the behaviour of a thread.
 start()
 run()
 yield()
 sleep()
 stop()
Java Program to use yield(), stop() and sleep() methods
class A extends Thread
{
public void run()
{
for (int i = 1; i<=5; i++)
{
if (i==1) yield();
System.out.println("\tFrom Thread A : i = "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("\tFrom Thread B : j = "+j);
if(j==3) stop();
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for (int k=1; k<=5; k++)
{
System.out.println("\tFrom Thread C : k = " +k);
if(k==1)
try{sleep(1000);}
catch(Exception e){}
}
class ThreadMethd
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();

System.out.println("Start thread A");


threadA.start();
System.out.println("Start thread B");
threadB.start();
System.out.println("Start thread C");
threadC.start();
System.out.println("End of main thread");
}
}
• A yield() method is a static method of Thread
class and it can stop the currently executing
thread and will give a chance to other waiting
threads of the same priority.
• If in case there are no waiting threads or if all
the waiting threads have low priority then the
same thread will continue its execution.

• The main thread died much earlier than the


other three threads.
Thread Exceptions
• The call to sleep() method is enclosed in a try
block and followed by a catch block.
• This is necessary because the sleep() method
throws an exception, which should be caught.
If we fail to catch the exception, program will
not compile
• Java run system will throw
IllegalThreadStateException whenever we
attempt to invoke a method that a thread cannot
handle in the given state.
• For example, a sleeping thread cannot deal with
the resume() method because a sleeping thread
cannot receive any instructions.
• The same is true with the suspend() method
when it is used on a blocked (Not Runnable)
thread
• Whenever we call a thread method that is likely
to throw an exception, we have to supply an
appropriate exception handler to catch it.
• The catch statement may take one of the
following forms:
catch (ThreadDeath e)
{ …………………
………………… // Killed thread
}

catch (InterruptedException e)
{ …………………
............// Cannot handle it in the current state
}
catch (Illegal ArgumentException e)
{ ……………………..
…………………… // Illegal method argument
}

catch (Exception e)
{ ……………….
…………….. // Any other
}
Thread Priority
• In Java, each thread is assigned a priority,
which affects the order in which it is
scheduled for running.
• The threads of the same priority are given
equal treatment by the Java scheduler and,
therefore, they share the processor on a first-
come, first-serve basis.
• Java permits to set the priority of a thread
using the setPriority() method as follows:
ThreadName.setPriority (intNumber);
• The intNumber is an integer value to which
the thread's priority is set.
• The Thread class defines several priority
constants:
• MIN_PRIORITY = 1
• NORM_PRIORITY = 5
• MAX_PRIORITY = 10
• Note:
We can get and set the priority values for
threads in Java using the getPriority() and
setPriority() methods.
Based on these priorities, the thread
scheduler decides the order of thread
execution.
We should also remember that there is no
guarantee that the scheduler always executes
the high priority threads first since it also
depends on the JVM implementation.
• Most user-level processes should use NORM_PRIORITY,
plus or minus 1
• By assigning priorities to threads, it ensure that they are
given the attention they deserve.
• For example, we may need to answer an input as
quickly as possible.
• Whenever multiple threads are ready for execution, the
Java system chooses the highest priority thread and
executes it.
• For a thread of lower priority to gain control, one of the
following things should happen:
1. It stops running at the end of run().
2. It is made to sleep using sleep().
3. It is told to wait using wait().
• However, if another thread of a higher priority
comes along, the currently running thread will
be preempted by the incoming thread thus
forcing the current thread to move to the
runnable state.
• Remember that the highest priority thread
always preempts any lower priority threads.
Synchronization
• Threads that use their own data and methods
provided inside their run() methods.
• What happens when they try to use data and
methods outside themselves?
• On such occasions, they may compete for the same
resources and may lead to serious problems.
• For example, one thread may try to read a record
from a file while another is still writing to the same
file.
• Depending on the situation, we may get strange
results
• Java enables us to overcome this problem
using a technique known as synchronization.
• In case of Java, the keyword synchronised
helps to solve such problems by keeping a
watch on such locations.
• For example, the method that will read
information from a file and the method that
will update the same file may be declared as
synchronized.
Ex: synchronized void update()
{…………………
………………… // code here is
}

• When we declare a method synchronized, Java


creates a "monitor" and hands it over to the
thread that calls the method first time.
• As long as the thread holds the monitor, no
other thread can enter the synchronized section
of code.
• A monitor is like a key and the thread that holds
the key can only open the lock.
• It is also possible to mark a block of code as
synchronized
synchronized (lock-object )
{…………………
…………………. // code here is synchronized
}
• Whenever a thread has completed its work of
using synchronized method (or block of code),
it will hand over the monitor to the next
thread that is ready to use the same resource.
• An interesting situation may occur when two
or more threads are waiting to gain control of
a resource.
• Due to some reasons, the condition on which
the waiting threads rely on to gain control
does not happen. This results in what is
known as deadlock.
• For example, assume that the thread A must
access Method1 before it can release Method2,
but the thread B cannot release Method1 until it
gets hold of Method2 Because these are
mutually exclusive conditions, a deadlock occurs.

Thread A Thread B
synchronized method2( ) synchronized method1( )
{ {
synchronized method1() synchronized method2()
{……………… {………………
……………….. ………………..
} }
} }
Implementing The 'Runnable' Interface
• How to make use of the Runnable interface to implement
threads.
• The Runnable interface declares the run() method that is
required for implementing threads in our programs.
• Steps
1. Declare the class as implementing the Runnable
interface.
2. Implement the run() method.
3. Create a thread by defining an object that is
instantiated from this "runnable" class as the target
of the thread.
4. Call the thread's start() method to run the
thread.
Java Program using Runnable Interface
class X implements Runnable
{
public void run()
{
for (int i = 1; i<=10; i++)
{
System.out.println("\tThreadX : " +i);
try{Thread.sleep(1000);}catch(Exception e){}
}
System.out.println("End of ThreadX");
}
}
class RunnableTest
{
public static void main(String args[])
{
X runnableobj = new X();
Thread threadobj = new Thread(runnableobj);
threadobj.start();
System.out.println("End of main Thread");
}

You might also like