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

Java Unit 2 Complete

The document provides an overview of Java interfaces, packages, and exception handling. It explains how to declare and implement interfaces, define and import packages, and manage exceptions using keywords like try, catch, throw, and finally. Additionally, it covers checked and unchecked exceptions, as well as nested try statements and the use of throws clauses in method declarations.

Uploaded by

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

Java Unit 2 Complete

The document provides an overview of Java interfaces, packages, and exception handling. It explains how to declare and implement interfaces, define and import packages, and manage exceptions using keywords like try, catch, throw, and finally. Additionally, it covers checked and unchecked exceptions, as well as nested try statements and the use of throws clauses in method declarations.

Uploaded by

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

PREPARED BY: SHAIK RASOOL, ASST. PROF.

, MJCET

Unit 2
2.1 Interfaces

An interface in Java is a blueprint of a class. It has static constants and abstract methods. It is
used to achieve abstraction.

2.1.1 Declaring interfaces

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.
• If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.

// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations
}

Example

interface Student
{
public static final total=750;
public static void studentRollNo(int id);
public void percentage(int total);
}

2.1.2 Implementing Interfaces

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

Syntax:

class ClassName implements interface

Example 1: Implementing an interface

interface Animal {
public void eat();
public void travel();
}

1
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Example 2: Implementing two interfaces

interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}

public void myOtherMethod() {


System.out.println("Some other text...");
}
}

class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

2
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

3.1.3 Extending Interfaces

An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

public interface Sports {


public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

2.2 Packages

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management. Package in java can be
categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

2.2.1 Defining a Package

To create a package is quite easy: simply include a package command as the first statement in
a Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.

package MyPackage;

Java uses file system directories to store packages. For example, the .class files for any

3
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
Remember that case is significant, and the directory name must match the package name
exactly. More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong.

You can create a hierarchy of packages. To do so, simply separate each package name from
the one above it by use of a period. The general form of a multileveled package statement is
shown here:

package pkg1[.pkg2[.pkg3]];

Example:

// A simple package package MyPack;


class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n; bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal); }
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];

current[0] = new Balance("K. J. Fielding", 123.23);


current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}

2.2.2 Importing Packages

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

4
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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();
obj.msg();
}
}

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();
}
}

5
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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();
}
}

2.3 Exception Handling

A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
to handle the exception itself or pass it on. Either way, at some point, the exception is caught
and processed. Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

6
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

This is the general form of an exception-handling block:

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}

Here, ExceptionType is the type of exception that has occurred.

2.3.1 Exception Types

Checked exceptions − A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}

If you try to compile the above program, you will get the following exceptions.

FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be


caught or declared to be thrown
FileReader fr = new FileReader(file);
^

7
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Unchecked exceptions − An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the 6th
element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class Unchecked_Demo {


public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

If you compile and execute the above program, you will get the following exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at


Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Exception Hierarchy

8
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

2.3.2 Using try and catch

Although the default exception handler provided by the Java run-time system is useful for
debugging, you will usually want to handle an exception yourself. To guard against and handle
a run-time error, simply enclose the code that you want to monitor inside a try block.
Immediately following the try block, include a catch clause that specifies the exception type
that you wish to catch.

class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

Displaying a Description of an Exception

The print method displays description as we pass the exception as an argument.

catch(Exception e)

System.out.println(e);

2.3.3 Multiple catch Clauses

In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, you can specify two or more catch clauses, each catching a different type
of exception. When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed. After one catch statement
executes, the others are bypassed, and execution continues after the try/catch block. The
following example traps two different exception types:

9
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

// Demonstrate multiple catch statements.


class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

2.3.4 Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack. If an
inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are inspected for a match. This continues
until one of the catch statements succeeds, or until all of the nested try statements are exhausted.
If no catch statement matches, then the Java run-time system will handle the exception. Here
is an example that uses nested try statements:

// An example of nested try statements.


class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
/* If no command-line args are present, the following statement will generate a
divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try
{
// nested try block
/* If one command-line arg is used, then a divide-by-zero exception will
be generated by the following code. */
if(a==1)

10
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

a = a/(a-a); // division by zero


/* If two command-line args are used, then generate an out-of-bounds
exception. */
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}

2.3.5 throw
It is possible for your program to throw an exception explicitly, using the throw statement. The
general form of throw is shown here:

throw ThrowableInstance;

The flow of execution stops immediately after the throw statement; any subsequent statements
are not executed. The nearest enclosing try block is inspected to see if it has a catch statement
that matches the type of exception. If it does find a match, control is transferred to that
statement. If not, then the next enclosing try statement is inspected, and so on. If no matching
catch is found, then the default exception handler halts the program and prints the stack trace.

11
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

2.3.6 throws

If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this
by including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

// body of method

Example:

class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}

2.3.7 finally

finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement matches the exception. The finally clause is optional.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;

12
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

2.3.8 Java’s Built-in Exceptions

13
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Inside the standard package java.lang, Java defines several exception classes. A few have been
used by the preceding examples. The most general of these exceptions are subclasses of the
standard type RuntimeException. As previously explained, these exceptions need not be
included in any method’s throws list. In the language of Java, these are called unchecked
exceptions because the compiler does not check to see if a method handles or throws these
exceptions.

The above table lists those exceptions defined by java.lang that must be included in a method’s
throws list if that method can generate one of these exceptions and does not handle it itself.
These are called checked exceptions. Java defines several other types of exceptions that relate
to its various class libraries.

2.3.9 Creating Your Own Exception Subclasses

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try
{

14
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}

2.4 Multithreading

Multithreading in java is a process of executing multiple threads simultaneously. 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 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.

Java Multithreading is mostly used in games, animation, etc.

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.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

2.4.1 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.

Commonly used Constructors of Thread class:

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

15
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Java Thread Methods:

S.N. Modifier and Method Description


Type
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 currentThread() It returns a reference to the currently
Thread 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 interrupted() It tests whether the current thread has
boolean 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 holdLock() It returns true if and only if the
boolean 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.

16
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

S.N. Modifier and Method Description


Type
26) StackTrace getStackTrace() It returns an array of stack trace
Element[] 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.Stat getState() It is used to return the state of the
e thread.
29) ThreadGrou getThreadGroup It is used to return the thread group to
p () 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 setContextClass It sets the context ClassLoader for the
Loader() Thread.
34) ClassLoade getContextClass It returns the context ClassLoader for
r Loader() the thread.
35) static getDefaultUnca It returns the default handler invoked
Thread.Unc ughtExceptionH when a thread abruptly terminates due
aughtExcep andler() to an uncaught exception.
tionHandler
36) static void setDefaultUnca It sets the default handler invoked
ughtExceptionH when a thread abruptly terminates due
andler() to an uncaught exception.

2.4.2 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.

Java Thread Example by extending Thread class


1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

17
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Java Thread Example by implementing Runnable interface


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }

2.4.3 Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 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.

18
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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.

2.4.4 Sleep method

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds)throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java


1. class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. t1.start();
13. t2.start();
14. }
15. }

2.4.5 The join() method

The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.

Syntax:

public void join()throws InterruptedException

19
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public void join(long milliseconds)throws InterruptedException

Example of join() method

1. class TestJoinMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. TestJoinMethod1 t1=new TestJoinMethod1();
12. TestJoinMethod1 t2=new TestJoinMethod1();
13. TestJoinMethod1 t3=new TestJoinMethod1();
14. t1.start();
15. try{
16. t1.join();
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22. }

2.4.6 getName(),setName(String) and getId() method

public String getName()


public void setName(String name)
public long getId()
1. class TestJoinMethod3 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestJoinMethod3 t1=new TestJoinMethod3();
7. TestJoinMethod3 t2=new TestJoinMethod3();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. System.out.println("id of t1:"+t1.getId());
11.
12. t1.start();
13. t2.start();
14.
15. t1.setName("Sonoo Jaiswal");
16. System.out.println("After changing name of t1:"+t1.getName());
17. }
18. }

20
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

2.4.7 The currentThread() method

The currentThread() method returns a reference to the currently executing thread object.

Syntax:

public static Thread currentThread()

Example of currentThread() method

1. class TestJoinMethod4 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestJoinMethod4 t1=new TestJoinMethod4();
8. TestJoinMethod4 t2=new TestJoinMethod4();
9.
10. t1.start();
11. t2.start();
12. }
13. }

2.4.8 Priority of a Thread (Thread Priority)

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

5. }
6. public static void main(String args[]){
7. TestMultiPriority1 m1=new TestMultiPriority1();
8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. }
14. }

21
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

2.4.9 isAlive() method

The isAlive() method of thread class tests if the thread is alive. A thread is considered alive
when the start() method of thread class has been called and the thread is not yet dead. This
method returns true if the thread is still running and not finished.

Syntax

public final boolean isAlive()

Return

This method will return true if the thread is alive otherwise returns false.

public class JavaIsAliveExp extends Thread


{
public void run()
{
try
{
Thread.sleep(300);
System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
}
catch (InterruptedException ie) {
}
}
public static void main(String[] args)
{
JavaIsAliveExp t1 = new JavaIsAliveExp();
System.out.println("before starting thread isAlive: "+t1.isAlive());
t1.start();
System.out.println("after starting thread isAlive: "+t1.isAlive());
}
}

2.4.10 Thread Synchronization

Synchronization in java is the capability to control the access of multiple threads to any shared
resource. There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive: Mutual Exclusive helps keep threads from interfering with one
another while sharing data. This can be done by three ways in java:
• Synchronized method.
• Synchronized block.
• static synchronization.
2. Cooperation (Inter-thread communication in java)

22
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Java synchronized method

• If you declare any method as synchronized, it is known as synchronized method.


• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

Example of java synchronized method

class Table
{
synchronized void printTable(int n)
{
//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e){System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

23
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Synchronized Block

Synchronized block can be used to perform synchronization on any specific resource of the
method. Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block

• Synchronized block is used to lock an object for any shared resource.


• Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

synchronized (object reference expression) {

//code block

class Table
{
void printTable(int n)
{
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try
{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);
}
}
}
}//end of the method
}

24
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

public class TestSynchronizedBlock1


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
class Table{

synchronized static void printTable(int n){


for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}

25
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

2.4.11 Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.

26
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public class TestDeadlockExample1 {


public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}

2.4.12 Inter-thread communication

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

27
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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:

• wait()
• notify()
• 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.

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()

class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try
{
wait();

28
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

}
catch(Exception e)
{
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run(){c.deposit(10000);
}
}.start();
}
}

29

You might also like