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

Unit Iii

This document discusses Java packages. It defines what a package is and describes two types of packages: built-in packages provided by Java and user-defined packages. It lists some common built-in packages like java.lang, java.util, java.io, and explains how to compile and run a program using a user-defined package. The document also covers accessing packages from other packages, package hierarchies with subpackages, and Java access specifiers.

Uploaded by

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

Unit Iii

This document discusses Java packages. It defines what a package is and describes two types of packages: built-in packages provided by Java and user-defined packages. It lists some common built-in packages like java.lang, java.util, java.io, and explains how to compile and run a program using a user-defined package. The document also covers accessing packages from other packages, package hierarchies with subpackages, and Java access specifiers.

Uploaded by

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

UNIT -III

packages :
package : A package is a group of similar types of classes, interfaces and sub-
packages. A package is a directory for holding java files. A package can be defined
as a collection used for grouping a variety of classes and interfaces based on their
functionality.

Packages in java can be categorized into two types

1. built-in packages

2. user-defined package.

Built-in packages :

java has many predefined packages which can be used in programs and are
given by sun micro systems. Some of them are java, lang, awt, javax, swing, net,
io, util, sql etc.

java.lang : consists of primary classes and interfaces essential for developing a


basic java program.

Java. math : provides classes for performing arbitrary-precision integer arithmetic


(BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal). This
reference will take you through simple and practical methods available in java.

java.util :Contains classes such as vectors, hash tables, date etc.

java.io:Stream classes for I/O

java.awt:Classes for implementing GUI – windows, buttons, menus etc.

java.net:Classes for networking

java.applet: Classes for creating and implementing applets


Advantage of Java Package

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.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. 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");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
10. obj.msg();
11. }
12. }
Output:Hello

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();
10. obj.msg();
11. }
12. }
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 impo
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();
}
10. }
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 interfa
subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.
Ex 2 :
package mypack;

class Addition
{
void sum(int a,int b)
{
System.out.println(“ sum = “ + (a+b));
}
}

save : Addition.java
compile: javac -d . Addition.java
----------------------------------
package mypack;
class Subtraction
{
void diff(int a,int b)
{
System.out.println(“Difference =” + (a-b));
}
}

save : Subtraction.java
compile : javac -d . Subtraction.java

-------------------------
package mypack;
import mypack.*;
class PackDemo
{
public static void main(String args[])
{
Addition a = new Addition();
Subtraction b = new Subtraction();
a.sum(10,20);
b.diff(10,20);
}
}
save : PackDemo.java
Compile : javac -d . PackDemo.java
Execute : java mypack.PackDemo

in the above programs , Addition and Subtraction ,PackDemo classes are placed in the package
called mypack. Any class can import the classes of the same package or from the other
packages.Here, PackDemo class is importing the classes from mypack. compile all the three
programs using the above commands and we can execute PackDemo class which is in mypack
package with the statement
“java mypack.PackDemo” or move to mypack directory and execute using the statement “ java
PackDemo” or you can set the CLASSPATH and then execute your program.
Setting the classpath:
if the class files are not in the current directory, we need to set the classpath.
Whenever, we execute / compile any class files, JDK tools javac and java , search the package /
class file in the user classpath which is the current directory by default. If the classes are not in
the current directory, then we need to set the classpath.
The classpath can be set in two ways :
1. It is an environment variable which can be set using the system utility in the control
panel or at the DOS prompt as shown:
set CLASSPATH = %CLASSPATH% ; d:\mypack;

%classpath% is used to keep the existing path intact and append our new path to it.

To make the changes permanent, edit the environment variable in the control panel
right click on
computer-> properties -> Advanced System Setting -> Engironment
variables -> classpath
2. To use user defined packages, we can use –classpath option
Ex : javac –cp “d:\mypack” PackDemo.java

Sub Packages :
sub packages can be designed in hierarchy i.e one package can be a part of another
package. This can be achieved by specifying multiple names of packages at various levels of
hierarchy separated by dots.

syntax :
package rootpackagename.subpackagename;
using packages :
To import all the classes in a package, we can use wildcard notation.
import java.awt.*;
to import a specific class we can specify the classname as
import java.awt.Rectangle;
classes in a package java.lang are automatically imported . For all other classes , you must
supply an import statement.
Example :
Recursive program to calculate factorial in a package.
package p1;
public class RecFactorial
{
public long fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n-1));
}
}
save : RecFactorial.java
compile : javac -d . RecFactorial.java
-------------------------------------------

package p2;
import p1.*;
class Test
{
public static void main(String args[])
{
RecFactorial obj = new RecFactorial();
System.out.println("factorial = " +obj.fact(5));
}
}
save : Test.java
compile :javac -d . Test.java
execute : java p2.Test

Access Specifiers :

An access Specifier is a keyword that specifies how to access the


members of a class or a class itself.

We can use access specifier before a class or its members. There are 4
access specifiers available in java.

1. private: The access level of a private modifier is only within the


class. It cannot be accessed from outside the class.
2. Default(blank): The access level of a default modifier is only
within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the
default.
3. protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
4. public: The access level of a public modifier is everywhere. It can
be accessed from within the class, outside the class, within the
package and outside the package.
we generally use ‘private’ for instance variables and public for
methods. In java, classes can not be declared by using ‘private’ because
they are not available to java compiler and hence compile time error
occurs. But, inner classes can be declared as private.

public,protected and default access specifiers look same, but there is


some difference between them.

Understanding Java Access Modifiers

Access within class within package outside package by subclass outside package
Modifier only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1.private :
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and PrivateEx. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.

class A
{
private int x;
private void display()
{
System.out.println("hello");
}
}
class PrivateEx
{
public static void main(String args[])
{
A obj = new A();
obj.x=10; // compile error, private variable can not be accessed outside the class
obj.display(); //compile error, private method cannot be accessed outside the class
}
}

Note:
If you make any class constructor as private, you cannot create the instance of that class from outside
the class.

2.Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3.Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

1. /save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Exception Handling
Exception :

An exception is an event which occurs during the execution of a program , that


interrupts the normal flow of the program instructions. Exceptions are events that arise due to
the occurrence of unexpected behavior in certain statements, interrupting the normal
execution of a program.

Basically an exception is a runtime error.

Exceptions can arise due to a number of reasons.

For ex:

1. Division by zero(ArithmeticException)
2. Accessing a file which is not present(FileNotFoundException)
3. failure of I/O operation(IOException)
4. Illegal use of null(NullPointerException)
5. Trying to access 6th element of array when it has 5 elements only
(ArrayIndexOutOfBoundsException)
There are predefined classes(mentioned in the parenthesis above) for all exception types
representing each situation. The topmost class in the hierarchy is java.lang.Throwable

Exception Hierarchy in java


All classes representing exceptional conditions are subclasses of the Exception class.

Difference between an exception and an error:

An exception is an error which can be handled. It means when an exception happens ,


the programmer can do something to avoid any harm. But an error which cannot be handled ,
it happens and the cannot do anything.

Types of Exceptions:

The sun micro systems has given 3 categories of exceptions.

1. checked exceptions
2. unchecked exceptions
3. error

1.checked exceptions:

the exceptions that are checked at compilation time by the javacompilerare called
“checked exceptions” . These are exceptional conditions that are internal to the application that
could be anticipated and recovered.

Ex : IOException, SQLException etc.


2.unchecked exceptions:

The exceptions that are checked by the JVM at runtime are known as unchecked
exceptions. These are exceptional conditions that are internal to the application and the
application usually cannot anticipate or recover from.

Ex : NULLPointerException, ArithmeticException, NumberFormatException,


ArrayIndexOutofBoundsException

3.Error :

These are exceptional conditions that are external to the application and that the
application usually cannot anticipate or recover from.

Ex : OutofMemoryError, VirtualMemoryError, AssertionError etc.

suppose that an application successfully opens a file for input but is unable to read the
file because of a hardware or software mall functioning. In this case it throws java.io.IOError

Exception Handling Techniques:

Java provides five keywords for exception handling

1.try
2.catch
3.throw
4.throws
5.finally

try ..catch:
the try/catch block can be placed within any method that you feel can throw exceptions.
All the statements to be tried for exceptions are put in a try block and immediately following
the try is the catch block.
catch block:
it is used to catch any exception raised from the try block. If exception rises in any
statements, then the following statements of that try block are not executed and control passes
to corresponding catch block.
finally :
The "finally" block is used to execute the important code of the program. It is executed whether
an exception is handled or not.
throw:
The "throw" keyword is used to throw an exception.
throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.
Ex :

public class JavaExceptionExample


{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Exception handling:
when there is an exception, the user data may be corrupted . This should be tackled by
java programmer by carefully designing the program. For this, he should perform the following
3 steps.
step1 :
The programmer should observe the statements in his program where there may be a
possibility of exceptions. such statements should be written inside a try block.
A try block looks like as follows
try
{
statements;
}
The greatness of try block is that even if some exception arises inside it, the program will not be
terminated. when JVM understands that there is an exception, it stores the exception
details in an exception stack and then jumps into a catch block.

step2 :
The programmer should write the catch block where he should display the exception
details to the user. This helps the user to understand that there is some error in the program.
The programmer should also display a message regarding what can be done to avoid this error.
catch block looks as follows:
catch(Exceptionclass ref)
{
statements;
-------
--------
}
step3 :
The programmer should perform clean up operations like closing the files and
terminating the threads. The programmer should write this code in the finally block.
finally block look like:
finally
{
// statements;
}

The specialty of finally block is that the statements inside the finally block are executed
irrespective of whether there is an exception or not.
performing the above three tasks is called exception handling.
try
{
----
----
}
catch(Throwable e)
{
---
---
}
finally
{
-----
-----
}
Ex : write java program which shows the use of try, catch and finally block.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
int n=25/0;
System.out.println(n);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Multiple catch clauses or Handling Multiple Exceptions:
most of the times there is possibility of more than one exceptionprsent in the program.
In this case, the programmer should write multiple catch blocks to handle each one of them.

Syntax :
try
{
statements
}
catch(ExceptionType1 e)
{
}
catch(ExceptionType2 e)
{
}
Ex : Write a program which shows how to handle the ArithmeticException and
ArrayIndexOutofBoundsException
class ExceptionTest
{
public static void main(String args[])
{
int b[]={10,20,30,40,50};
try
{
int a=5/0;
System.out.println(a);
System.out.println(b[5]);
}
catch(ArithmeticException e)
{
System.out.println("divide by zero error");
}

catch(ArrayIndexOutofBoundsException e)
{
System.out.println(“please see that array index is within the range”);
}
}
throw clause :
there is also a throw statement available in java to throw an exception explicitly and
catch it.It is used to throw our own exception.

Ex:

class ExceptionTest
{
public static void main(String args[])
{
int a=10, b=0,c;
try
{
if(b==0)
throw new ArithmeticException(“divisor is zero”);
else
{
c=a/b;
System.out.println(c);
}
}
catch(ArithmeticException e)
{
System.out.println(“Exception handled “ + e);
}
}
}

The throws keyword:


If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method’s signature.Otherwise,
there will be an error flagged by java compiler.
The throws is added to the method signature to let the caller know about what
exceptions the called method can throw. It is the responsibility of the caller to either handle the
exception or it can also pass the exception.

Syntax of java throws


return_type method_name() throws exception_class_name
{
//method code
}

Ex:
class ExceptionTest3
{
static void fun() throws ArithmeticException
{
int a=12;
System.out.println(a/0);
}

public static void main(String args[])


{

try
{
fun();
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block executed");
}
}
}

The exceptions available in java are


1. built – in exceptions
2. user – defined – exceptions

in java, we can create our own exceptions, i.e. user-defined


exceptions.

user-defined exceptions:
sometimes, the built – in exceptions in java are not able to describe a certain situation. In
such cases, the user can create his own exceptions which are called user-defined exceptions.

steps to follow to create user-defined exceptions are:

1. the user should create an exception class as a subclass to exception class. Since all
exceptions are subclasses of exception class, the user should also make his class a
subclass to it.
this is done as
class MyException extends Exception

2. The user can write a default constructor in his own exception class. He can use it, in case
he does not want to store any exception details. If the user does not want to create an
empty object to his exception class, he can eliminate writing the default constructor.
MyException()
{

}
3. The user can create a parameterized constructor with a string as a parameter. He can
use this to store exception details. He can call super class(Exception) Consturctions from
this and send the string there.
MyException(String s)
{
super(s);
}
4. when the user wants to raise his own exception, he should create an object to his
exception class and throw it using throw clause as.
MyException m=new MyException(“Exception details”);
throw m;

Ex:
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class ExceptionTest4
{

public static void main(String args[])


{
try
{
// Throw an object of user defined exception
throw new MyException("user defined exception");
}
catch (MyException e)
{
System.out.println("Caught :" + e);
}
}
}

Assertions :
Assertions are Boolean expressions that are used to test/validate the code. They are basically
used during testing and development phases. They are added in java 1.4 to creat reliable
programs that are correct and robust.
Ex:
conditions such as a number is positive or negative , array / reference is null or
notcan be checked by asserting them.
Assertions in java are declared with the help of assert keyword as
assert expression1; // assert x>0;
or
assert expression1 : expression2 // assert x<0: “value ok”;

where expression1 is the condition to be evaluated. Incase, the condition evaluated is


false an AssertionError is thrown. Expression2 is a string which is passed to the
constructor of the AssertionError object.

Assertions have to be enabled explicitly ; they are disabled by default. Using the –ea and
–da options of java, we can enable and disable assertions.
-ea enable assertions

-da disable assertions


Ex :
class AssertDemo
{
static void check(int i)
{
assert i>o:”value must be positive”;
System.out.println(“value fine “+i);
}
public static void main(String arg[])
{
check(Integer.parseInt(args[0]);
}
}
MULTITHREADING IN JAVA

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved in two ways:

1. Process-based Multitasking (Multiprocessing)

2. Thread-based Multitasking (Multithreading)

Process-based Multitasking (Multiprocessing)

• Each process has an address in memory. In other words, each process allocates a separate
memory area.

• A process is heavyweight.

• Cost of communication between the process is high.

• Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

Thread-based Multitasking (Multithreading)


• Threads share the same address space.

• A thread is lightweight.

• Cost of communication between the thread is low.

Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

A thread is executed inside the process.

There is context-switching between the threads.

There can be multiple processes inside the OS, and one process can have multiple threads.

Note: At a time one thread is executed only.


Java Thread class
Java provides Thread class to achieve thread programming.

Thread class provides constructors and methods to create and perform operations on a thread.

Thread class extends Object class and implements Runnable interface.

Methods available in Thread class are:

S.N. Modifier and Type Method Description

1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread() It returns a reference to the currently executing


thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread object to
pause and allow other threads to execute
temporarily.

13) void suspend() It is used to suspend the thread.


14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and all of its
subgroups.

17) boolean isDaemon() It tests if the thread is a daemon thread.

18) void setDaemon() It marks the thread as daemon or user thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been interrupted.

21) static boolean interrupted() It tests whether the current thread has been
interrupted.

22) static int activeCount() It returns the number of active threads in the
current thread's thread group.

23) void checkAccess() It determines if the currently running thread has


permission to modify the thread.

24) static boolean holdLock() It returns true if and only if the current thread holds
the monitor lock on the specified object.

25) static void dumpStack() It is used to print a stack trace of the current thread
to the standard error stream.

26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements


representing the stack dump of the thread.

27) static int enumerate() It is used to copy every active thread's thread group
and its subgroup into the specified array.

28) Thread.State getState() It is used to return the state of the thread.

29) ThreadGroup getThreadGroup() It is used to return the thread group to which this
thread belongs

30) String toString() It is used to return a string representation of this


thread, including the thread's name, priority, and
thread group.
31) void notify() It is used to give the notification for only one
thread which is waiting for a particular object.

32) void notifyAll() It is used to give the notification to all waiting


threads of a particular object.

33) void setContextClassLoader() It sets the context ClassLoader for the Thread.

34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the thread.

35) static getDefaultUncaughtExcepti It returns the default handler invoked when a thread
Thread.UncaughtExceptionHan onHandler() abruptly terminates due to an uncaught exception.
dler

36) static void setDefaultUncaughtExcepti It sets the default handler invoked when a thread
onHandler() abruptly terminates due to an uncaught exception.

Life cycle of a Thread (Thread States)

The life cycle of the thread in java is controlled by JVM.

The java thread states are as follows:


1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1)New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.

How to create thread in java


There are two ways to create a thread:

1.By extending Thread class

2. By implementing Runnable interface

1.By extending Thread class

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

2.By implementing Runnable interface.

Runnable interface:
• The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread.
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Ex : write a program to create a new thread by extending Thread class
class MyThread extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
MyThread t = new MyThread();
t.start();
}
}

Ex2 :program to create multiple threads using Thread class


class MyThread1 extends Thread
{
String name;
int time;
MyThread1(String n,int t)
{
name=n;
time=t;
}

public void run()


{
for(int i=0;i<10;i++)
{
System.out.println(name + " is executing");
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

public static void main(String args[])


{
MyThread1 t1= new MyThread1("Thread1",1000);
MyThread1 t2= new MyThread1("Thread2",2000);
MyThread1 t3= new MyThread1("Thread3",3000);
t1.start();
t2.start();
t3.start();
}
}

Creating a new thread by implementing Runnable interface

new threads can be created by creating a class that implements the Runnable
interface.
Steps to be followed for thread creation are :

1. declare your own class implementing the Runnable interface


class classname implements Runnable
{

}
2. after implementing Runnable interface , the class need to implement the run()
method, which is of form
public void run()
{

}
the code that thread will execute is placed insidethe run() method.

run() method can call other methods.


thread will end when run() method terminates.
3. An object of the Thread class must be instantiated from within your class
Ex : creating a new thread using Runnable interface
class ThreadEx1 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[])


{
ThreadEx1 obj=new ThreadEx1();
Thread t =new Thread(obj);
t.start();
}
}

Ex : creating multiple threads using Runnable interface

class MultiThreadR implements Runnable


{

String s;
int time;
MultiThreadR(String s, int t)
{
this.s = s;
time = t;
Thread t1= new Thread(this);
t1.start();
}
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(s);
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
public static void main(String args[])
{
new MultiThreadR("Thread1",1000);
new MultiThreadR("Thread2",2000);
new MultiThreadR("Thread3",3000);
}
}

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}

Thread Synchrnization:

There can be instances when two or more threads access a common resource, say a common
data or file. In order to maintain consistency, it becomes important that the resource is made available
to only one thread at a time.

Ex : If there are two threads, one responsible for writing to a file and other for reading from the same
file. If both the threads start concurrentlye , both would try to access the file at the same time.
Obsivously , if the first thread has not written the values completely, the values read by the second
thread would be inconsistent.

Java has such in built mechanism, which lets only one thread use a resource at a time known as
synchronization. To do this, we have the concept of monitors here. Monitor is an object that is used as a
mutually exclusive lock on the resource to be accessed.

A monitor can be owned by only one thread at a time. A thread enters the monitor as soon as it acquires
the lock. All the other threads cannot enter the locked monitor, unless it is unlocked or the first thread
exits the monitor. During this period, other threads are waiting for the lock on the monitor. If a thread
exits the monitor , it can again enter the same monitor at some later stage.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

• Mutual Exclusive

– Synchronized method.

– Synchronized block.

• Cooperation (Inter-thread communication in java)

Synchronizing mechanism mentioned above can be achieved in java in two ways.

1. Synchronized methods(by using synchronized keyword with method definition)


2. synchronized statements.(by using synchronized keyword with block of code)
1) synchronized methods:
Here, we use synchronized keyword with method definition as
class xyz
{
synchronized methodx()
{

}
}

Now, if n number of threads want to use the method(), the system will not allow them to do so. the
highest priority thread will lock the monitor for the method making it inaccessible to other threads.
Once the thread locking for the monitor finishes its job , it releases the monitor for the use of other
waiting threads.

2) synchronized statements:

There are two methods suspend() and resume() used for suspending an executing
thread temporarily and resuming the suspension, respectively.

suspend():

this method puts a thread in suspended state and can be resumed using
resume() method.
resume():

This method resumes a thread which was suspended using suspend() method.

Ex : write a java program for illustrating synchronized method.

class Table
{
synchronized void printable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n + “ * “ + i + “=” + (n*i));
try
{
Thread.sleep(400);
}
catch(InterruptedException e)
{
System.out.println€;
}
}
}
}
class MyThread1 exabtends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

class MyThread2 exabtends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(7);
}
}
public class SynchronizationEx
{
public static void main(String args[])
{
Table tb=new Table();
MyThread1 t1= new MyThread1(tb);
MyThread1 t2= new MyThread1(tb);
t1.start();
t2.start();
}
}

Ex : java program to illustrate synchronized block

class Table
{
void printTable(int n)
{
for(int i=1;i<=10;i++)
{
System.out.println(n + "* " + i + "="+ (n*i));
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
synchronized(t)
{
t.printTable(5);
}

}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
synchronized(t)
{
t.printTable(7);
}
}
}
public class SynchronizationEx1
{
public static void main(String args[])
{
Table tb=new Table();
MyThread1 t1= new MyThread1(tb);
MyThread2 t2= new MyThread2(tb);
t1.start();
t2.start();
}
}

Inter-thread communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed. It is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws InterruptedException waits for the specified amount
of time.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation. Syntax:
public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

You might also like