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

JavaProgramming notes-Unit2

Uploaded by

ssgaming1910
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views51 pages

JavaProgramming notes-Unit2

Uploaded by

ssgaming1910
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 51

PACKAGES

DEFINING PACKAGE:
Packages are containers for classes that are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.

A package is a container of classes and interfaces. A package represents a directory


that contains related group of classes and interfaces. For example, when we write
statemens like:

import java.io.*;

Here we are importing classes of java.iopackage. Here, javais a directory name and
iois another sub directory within it. The ‘*’represents all the classes and interfaces of
that io sub directory. We can create our own packages called user-defined packages
or extend the available packages. User-defined packages can also be imported into
other classes and used exactly in the same way as the Built-in packages.

USE: Packages provide re-usability.

ADVANTAGES OF PACKAGES:

Packages are useful to arrange related classes and interfaces into a group. This
makes all the classes and interfaces performing the same task to put together in the
same package. For example , in Java, all the classes and interfaces which perform
input and output operations are stored in java.io. package.

Packages hide the classes and interfaces in a separate sub directory, so that accidental
deletion of classes and interfaces will not take place.

The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes. For example, there is a Date class in java.util package and also there is
another Date class in java.sql package.

A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times. This reusability nature of packages
makes programming easy.
Just think, the package in Java are created by JavaSoft people only once, and millions
of programmers all over the world are daily by using them in various programs.

Different Types of Packages:

There are two types of packages in Java.

They are: Built-in packages

User-defined packages

Built-in packages:
These are the packages which are already available in Java language. These packages
provide all most all necessary classes, interfaces and methods for the programmer to
perform any task in his programs. Since, Java has an extensie library of packages, a
programmer need not think about logic for doing any task. For everything, there is a
method available in Java and that method can be used by the programmer without
developing the logic on his own. This makes the programming easy. Here, we introduce
some of the important packages of Java SE:

Java.lang:langstandsforlanguage.Thispackagegotprimaryclassesandinterfacesessential
for developing a basic Java program. It consists of wrapper classes(Integer, Character,
Float etc), which are useful to convert primitive data types into objects. There are
classes like String, SttringBuffer, StringBuilder classes to handle strings. There is a
thread class to create various individual processes. Runtime and System classes are
also present in java.lang package which contain methods to execute an application and
find the total memory and free memory available inJVM.

Java.util:util stands for utility. This package contains useful classes and interfaces
like Stack, LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections.
There are also classes for handling Date and Time operations.

Java.io:io stands for input and output. This package contains streams. A stream
represents flow of data from one place to another place. Streams are useful to store
data in the form of files and also to perform input-output relatedtasks.

Java.awt:awt stands for abstract window toolkit. This helps to develop GUI(Graphical
user Interfaces) where programs with colorful screens, paintings and images etc., can
be developed.
It consists of an important sub package, java.awt.event, which is useful to provide
action for components like push buttons, radio buttons, menus etc.

Javax.swing:this package helps to develop GUI like java.awt. The ‘x’ in javax
represents that it is an extended package which means it is a package developed from
another package by adding new features to it. In fact, javax.swing is an extended
package ofjava.awt.

Java.net:net stands for network. Client-Server programming can be done by using this
package. Classes related to obtaining authentication for network, creating sockets at
client and server to establish communication between them are also available in
java.netpackage.

Java.applet:applets are programs which come from a server into a client and get
executed on the client machine on a network. Applet class of this package is useful to
create and use applets.

Java.text:this package has two important classes, DateFormat to format dates and
times, and NumberFormat which is useful to format numericvalues.

Java.sql:sql stands structured query language. This package helps to connect to


databases like Oracle or Sybase, retrieve the data from them and use it in a Java
program.

User-Defined packages:
Just like the built in packages shown earlier, the users of the Java language can also
create their own packages. They are called user-defined packages. User-defined
packages can also be imported into other classes and used exactly in the same way as
the Built-in packages.

CREATING AND IMPORTING PACKAGES:

package packagename; //to create a package

package packagename.subpackagename;//to create a sub package within a

package. e.g.: package pack;


The first statement in the program must be package statement while creating a package.

While creating a package except instance variables, declare all the members and
the class itself as public then only the public members are available outside the
package to other programs.

Program 1: Write a program to create a package pack with Addition class.

package pack;

public

classAddition

{ private double d1,d2;

public Addition(double a,double b)

{ d1 = a;

d2 = b;}

public void sum()

{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );

}}

Compiling the above program:


javac -d . Addition.java
The –d option tells the Java compiler to create a separate directory and place the
.class file in that directory (package). The (.) dot after –d indicates that the package
should be created in the current directory. So, out package pack with Addition class
isready.

Program 2: Write a program to use the Addition class of package pack.

//Using the package

pack import

pack.Addition; class

Use

{ public static void main(String args[])

{ Addition ob1 = new Addition(10,20);

ob1.sum();

}
}

Output:

Program 3: Write a program to add one more class Subtraction to the same package
pack.

//Adding one more class to package

pack: package pack;

public class Subtraction

private double d1,d2;

public Subtraction(double a, double b)


{

d1 = a;

d2 =

b;

public void difference()

{ System.out.println ("Sum of two given numbers is : " + (d1 - d2) );

Compiling the above program:

Program 4: Write a program to access all the classes in the package pack.

//To import all the classes and interfaces in a class using import
pack.*; import pack.*;

class Use

{ public static void main(String args[])

{ Addition ob1 = new Addition(10.5,20.6);

ob1.sum();

Subtraction ob2 = new

Subtraction(30.2,40.11); ob2.difference();

}
In this case, please be sure that any of the Addition.java and Subtraction.java programs
will not exist in the current directory. Delete them from the current directory as they
cause confusion for the Java compiler. The compiler looks for byte code in
Addition.java and Subtraction.java files and there it gets no byte code and hence it flags
some errors.

UNDERSTANDING CLASSPATH:

If the package pack is available in different directory, in that case the compiler should be
given information regarding the package location by mentioning the directory name of
the package in the classpath.

The CLASSPATH is an environment variable that tells the Java compiler where to look
for class files toimport.

If our package exists in e:\sub then we need to set class path as follows:

We are setting the classpath to e:\sub directory and current directory (.) an
%CLASSPATH% means retain the already available classpath as it is.

Creating Sub package in a package: We can create sub package in a package in the
format: package packagename.subpackagename;

e.g.: package pack1.pack2;

Here, we are creating pack2 subpackage which is created inside pack1 package.
To use the classes and interfaces of pack2, we can write import statement as:

import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.

//Creating a subpackage in a

package package pack1.pack2;

public class Sample

{ public void show ()

System.out.println ("Hello Java Learners");

Compiling the above program:

ACCESSING A PACKAGES:
Access Specifier: Specifies the scope of the data members, class and methods.
private members of the class are available with in the class only. The scope of
private members of the class is “CLASS SCOPE”.

public members of the class are available anywhere . The scope of public members
of the class is "GLOBAL SCOPE".

default members of the class are available with in the class, outside the class and
in its sub class of same package. It is not available outside the package. So the
scope of default members of the class is "PACKAGE SCOPE".

protected members of the class are available with in the class, outside the class and in
its sub class of same package and also available to subclasses in different package
also.
Program 6: Write a program to create class A with different access specifiers.

//create a package

same package same;

public class A

{ private int a=1;

public int b = 2;

protected int c =

3; int d = 4;

Compiling the above program:

Program 7: Write a program for creating class B in the same package.

//class B of same

package package

same;

import

same.A;

public class

{
public static void main(String args[])

A obj = new A();

System.out.println(obj.a

);

System.out.println(obj.b

);

System.out.println(obj.c

);

System.out.println(obj.d

);

}}

Compiling the above program:

Program 8: Write a program for creating class C of another package.

package

another;

import same.A;

public class C extends A


{
public static void main(String args[])
{

C obj = new C();

System.out.println(obj.a);

System.out.println(obj.b);

System.out.println(obj.c);
System.out.println(obj.d);

Compiling the above program:

DEFINING AN INTERFACE AND IMPLEMENTING AN


INTERFACE :
A programmer uses an abstract class when there are some common features
shared by all the objects. A programmer writes an interface when all the features
have different implementations for different objects. Interfaces are written when the
programmer wants to leave the implementation to third party vendors. An interface is
a specification of method prototypes. All the methods in an interface are
abstractmethods.

An interface is a specification of method

prototypes. An interface contains zero or more

abstract methods.

All the methods of interface are public, abstract by default.

An interface may contain variables which are by default public static

final. Once an interface is written any third party vendor can

implement it.

All the methods of the interface should be implemented in its implementation classes.

If any one of the method is not implemented, then that implementation class should be
declared as abstract.
Exception Handling
Exception
Is an abnormal condition that arises in a code sequence at runtime.
Java Exception is an object that describes an exceptional condition that has occured
in a piece of code.
When an exceptional condition arises, an Object representing that exception is
created and thrown in the method that causes the error.
The method may choose to handle it or pass it to its caller.
Caller may choose to handle it or pass it to its caller. And so on till main method.
If main is also not interested to process the exception, then it will be thrown to JRE,
which uses default Exception Handler mechanism to process it.
Exception can be generated by JRE or can be manually generated.
keywords
Exception handling is managed via the following keywords
try
catch
finally
Throw
Throws
try block
Program statements that you want to monitor for exception are kept in the try block.
If an exception occured in the try block, it is thrown to its catch block.
Catch block
To process the Exception
That is write the code (may vary for each type of exception) that should get executed
when an exception is raised.
A try block can follow multiple catch blocks.
Each catch block can process a specific type of exception.
In multiple catch statements it is imortant to remember that exception subclasses
must come before any of their super classes.
From java 1.7 , java support multi catch blocks.
finally block
This block get executed after the completion of try block.
This block gets executed irrespective of whether the exception is raised or not, if
raised wheter it is handled or not.
Useful for closing file handles and freeing up of any other resources that might have
been allocated at the begining.
Every try block must be followed by at least one catch block or finally block.
try with resources
Runtime automatically closes the resources (if they are not already closed) after the
excecution of the try block.
try( BufferedReader br=
new FileReader(“ex1.txt”) ) {
}
catch(){}
This works only on classes that have implemented AutoCloseable interface.
Exception Types
Throwable
Exception
ClassNotFoundException(checked)
IOException
InterruptedException

RuntimeException(un checked)
ArithmeticExcepton
NumberFormatException
ArrayIndexOutOfBoundsException
ExceptionInInitializerError
Error
Un caught Exceptions
Class Ex1
{
pubic static void main(String args[])
{
int d=0;
int a=40/d;
}
}
Exception caught by default Exception handler of JRE.
Displays the string describing the exception, prints the stack trace from the point at
which exception occured and terminates the program.
Java.lang.ArithmeticException: / by Zero
at Ex1.main (Ex1.java : 6)
Example2
Class Ex1
{
static void meth1(){
int d=0; int a=40/d;
}
pubic static void main(String args[])
{
meth1();
}
}
Exception raised in meth1(), not handled, thrown to main(), not handled, thrown to
JRE.Exception caught by default Exception handler of JRE.
prints the stack trace as follows
Java.lang.ArithmeticException: / by Zeo
at Ex1.meth1 (Ex1.java : 4)
at Ex1.main (Ex1.java : 8)
Example_Porgram:
/*program with the following statements and observe the output.
System.out.prinrtn("Hello");
System.out.printtn("NGIT");
System.out.prinrtn(10/0);
System.out.prinrtn("Have a nice day");
System.out.prinrtn("Bye");
*/
class demo1
{
public static void main(String args[])
{
System.out.println("Hello");
System.out.println("NGIT");
System.out.println(10/0);
System.out.println("Have a nice day");
System.out.println("Bye");
}
}
Advantage of Handling an Exception
Stops abnormal termination.
Instead of printing the stack trace we can display user friendly messages to the user
related to the exception.
Allows us to fix the error.
Example_Program:
/* to demonstrate advantage of handling exception.
program to get the following output in same order
Use exception handling
Hello
NGIT
10/0 is invalid operation
All the Best
Bye
*/
class demo2
{
public static void main(String rags[])
{
System.out.println("Hello");
System.out.println("NGIT");
try
{

System.out.println(10/0);
}
catch(ArithmeticException ae)
{
System.out.println(ae.getMessage());
System.out.println(ae);
}
System.out.println("All the Best");
System.out.println("Bye");
}
}
Example_Program:
//demonstration of finally block.
class demo3
{
public static void main(String[] args)
{
int a=1,b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException ae)
{
System.out.println(" Error: denominotor cant be zero");
}
finally
{
System.out.println("This will execute");
}
}
}
Example_Program:
// To demonstration finally block another example
class demo4
{
public static void main(String[] args)
{
int a=10,b=5,c;
try
{
c=a/b;
System.out.println("result= "+c);
}
catch(ArithmeticException ae)
{
System.out.println(" Error "+ae);
}
finally
{
System.out.println("This will execute");
}
}
}
Example_Program:
/*Program to demonstrate ArrayIndexOutOFBoundsException*/
class demo5
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};
System.out.println(a[0]);
System.out.println(a[1]);
try
{
System.out.println(a[5]);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("Invalid index");
}
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
}
}
Example_Program:
/*program to demonstrate NullPointerException for Scanner class object
*/
import java.util.*;
class demo6
{
public static void main(String args[])
{
Scanner s=null;
try
{
int a=s.nextInt();
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
System.out.println("End of the program");
}
}

Multiple Catch blocks


Each catch block is to process the Exception
That is write the code (may vary for each type of exception) that should get executed
when an exception is raised.
A try block can follow multiple catch blocks.
Each catch block can process a specific type of exception.
In multiple catch statements it is imortant to remember that exception subclasses
must come before any of their super classes.
From java 1.7 , java support multi catch blocks.
Multi-catch block
Allows two or more exceptions to be caught by the same catch clause.
Used when two or more catch blocks has the same code.
Each multi catch parameter is implicitly final. So it can't be assigned a new value.

Example

int a=10,b=0; int vals[]={1,2,3};


try{
int result=aa/b; vals[10]=19;
}
catch(ArithmeticException |
ArrayIndexOutOfBoundsException e)
{
s.o.p(“Exception caught:” + e);
}

Example_Program:
//To demonstrate multiple catch blocks
class demo7
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
// int c=a[10]/0;
int c=a[1]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException ae)
{
System.out.println(" Error "+ae);
}
catch(ArrayIndexOutOfBoundsException ab)
{
System.out.println("Error : "+ab);
}
finally
{
System.out.println("this will execute");
}
}
}
Example_Program:
//To demonstrate multi-catch block
class demo8
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
int c=a[10]/0;
// int c=a[1]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException ae)
{
System.out.println("Error : "+ae);
}
finally
{
System.out.println("this will execute");
}
}
}
Example_Program:
//To demonstrate catch all catch block
class demo9
{
public static void main(String[] args)
{
int a[]={10,20,30,40,50,60};
try
{
int x=Integer.parseInt("5a");
int c=a[10]/0;
System.out.println("result= "+c);
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException ae)
{
System.out.println("Error : "+ae);
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
finally
{
System.out.println("this will execute");
}
}
}

Exceptions with Nested try blocks


Example_Program:
import java.util.*;
class demo10
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the number");
int a=s.nextInt();
try
{
int b=10/a;
System.out.println(b);
try
{
if(a==1) a=a/(a-a);
else
{
int c[]={1,2,3};
c[4]=4;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Invalid index");
}
}
catch(ArithmeticException e)
{
System.out.println("Divide be zero Error");
}
}
}
Exceptions with Nested method calls
Example_Program:
import java.util.*;
class demo11
{
static void meth1(int a)
{
try
{
if(a==1) a=a/(a-a);
else
{
int c[]={1,2,3};
c[4]=4;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Invalid index");
}
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the number");
int a=s.nextInt();
try
{
int b=10/a;
System.out.println(b);
meth1(a);
}
catch(ArithmeticException e)
{
System.out.println("Divide be zero Error");
}
}
}

Throw
To Manually throw an exception object.
Syntax:
throw throwable_instance.
The object thowable_instance must be an instance of Throwable class type.
When you manually throw an exception object from the try block ,it checks for the
matching catch block among the catch blocks which follows the try block.
If there is a match, the exception is caught by that catch block and it can process that
exception(optional).
After processing, if needed the method can rethrow the exception object to its caller
to give an oppurtunity to the caller to know about this exception and to process.
This caller can rethrow the exception object to its caller. And so on.

If ther is no matching catch block, the exception object is thrown to its caller.
If the caller also does not handle that exception, it will be thrown to its caller and so
on till the main method.
If main method also do not handle it, it will be thrown to JRE.
At a time we can throw only one Exception object.
If we need to report more that one exception, we need to chain the exceptions with
their cause exceptions.
Example_Program:
// To demonstrate throw keyword
class demo12
{
static void meth1()
{
try
{
int x=12/0;
}
catch(ArithmeticException e)
{
System.out.println("caught inside method:"+e);
throw e;
}
}
public static void main(String args[])
{
try
{
meth1();
}
catch(ArithmeticException e)
{
System.out.println("Recaught:"+e);
}
}
}
Example_Program:
// To demonstrate throw keyword- another example
class demo13
{
static void meth1()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("caught inside method:"+e);
throw e;
}
}
public static void main(String args[])
{
try
{
meth1();
}
catch(NullPointerException e)
{
System.out.println("Recaught:"+e);
}
}
}

Throws

If a method is capable of causing an exception that it does not handle, it must specify
this behaviour so that callers of this method can guard themselves against that
exception.
Not necessary for exceptions that are subclasses of RuntimeException class.

thows clause for an overriden method

The overridden method can declare the same exceptions as that of its super class.
The overridden method can be defined as not throwing any exceptions.
Can add any new RuntimeExceptons (un checked).
Can't and any new Checked Exceptions.
Can narrow down to the Exception subclasses declared in the parent class.
Can't specify super classes of the chekced exceptions declared in the parent class.

final rethrow /more precise rethrow


Class Ex1{
public static meth1(int x) throws IOException,InterruptedException {
try{
if(x==0) throw new IOException();
else throw new InterruptedException();
}
catch(Exception e){
throw e;
}}

public static void main(String args[])


{
try
{
meth1(0);
}
catch(IOException e){}
catch(InterruptedException e){}
}}
Example_Program:
// To demonstrate throws keyword
import java.io.*;
class demo14
{
static void meth1() throws FileNotFoundException
{
FileInputStream fis=null;
fis=new FileInputStream("ex1.dat");
}
public static void main(String args[])
{
try
{
meth1();
}
catch(FileNotFoundException e)
{
System.out.println("plz check your filename");
}
}
}

Example_Program:
// To demonstrate final rethrow

import java.io.*;

class demo15
{
static void meth1(int x) throws IOException,InterruptedException
{
try
{
if(x == 0)
throw new IOException();
else
throw new InterruptedException();
}
catch(Exception e)
{
throw e;
}

}
public static void main(String args[])
{
try
{
meth1(0);
}
catch(IOException | InterruptedException e)
{
System.out.println(e);
}
}
}

User defined exceptions

we can create our own Exceptions by extending from the class Exception.
Example_Program:
// User defined exceptions
import java.util.*;
class Vote extends Exception
{
Vote(String str)
{
super(str);
}
}

class demo16
{
public static void meth1(int age) throws Vote
{
if(age<18)
throw new Vote("Not eligible to vote");
System.out.println("Eligible to vote");
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter your age:");
int age=s.nextInt();
try
{
meth1(age);
}
catch(Vote v)
{
System.out.println("Error "+v);
}
}
}
Multithreading
Multitasking
Executing multiple tasks simultaneously.
Each task consists of cpu bound instructions and I/O bound instructions.
During I/O instruction execution, the cpu(processor) will be idle.
Multi tasking utilizes this time by assigning others tasks to the processor.
By making processor busy, the throughput (number of jobs that can be completed in
unit time) can be increased.
OS will use different cpu scheduling algorithms to share processor time among
multiple tasks.
A task can be atleast a program. We cant further subdivide.

Advantages
Reduces idle time of the cpu (increase throughput)
Quick response time.

Multithreading
Specialized form of multitasking.
Each task can be a thread.
A program can consists of two or more threads that can run concurrently.
Each thread defines a separate path of execution.

Threads are light weight, they share the same address space.
Context switching is easier.
Java provides built in support for multithreading.
In java the execution of main method itself is a thread created automatically when the
program started.

Example_Program: To demonstrate main thread


class demo0
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(t);
t.setName("thread1");
System.out.println(t);
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("i = "+i);
}
}
}

Creating a thread
We can create a new thread in two ways
1. by extending Thread class.
2. by implementing Runnable interface.

With Runnable interface


Create a class by implementing Runnable interface.
Ex: class A implements Runnable

The Runnable interface has only one method


public void run()
Provide implementation for that method (ie write business logic )

Create the Thread instance as


Thread t= new Thread(new A());
the argument to the Thread constructor is an object of the class that implements
Runnable interface.
To start the excution of your thread, call t.start().
This invokes the run() method of the thread to execute the business logic of the
thread.

Example_Program: Write a program to create a thread by implementing


interface Runnable

class MyThread implements Runnable


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread:"+i);
}
}
}
class demo2
{
public static void main(String args[])
{
MyThread m=new MyThread();
Thread t1=new Thread(m);
t1.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread:"+i);
}
}
}

Example_Program: Write a program to create a thread by implementing


interface Runnable-adding sleep()

class MyThreaEd implements Runnable


{
public void run()
{
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Child Thread:"+i);
}
}
}
class demo3
{
public static void main(String args[])
{
MyThread m=new MyThread();
Thread t1=new Thread(m);
t1.start();
for(int i=0;i<10;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Main Thread:"+i);
}
}
}

Extending Thred class


Create a subclass of Thread class.
Provide implementation for the run method.
To start the execution of the thread, call start() on the subclass object.

sleep()
Syntax: sleep(long millisec);
Static method
Makes the current thread to suspend its execution for specified millis secods.
If the thread is interrupted before the sleep time expires, it throws
InterruptedException.

Example_Program : program to create a thread by extending Thread


class.
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread :"+i);
}
}
}

class demo1
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread:"+i);
}
}
}

Creating and Working with Multiple Threads

Example_Program: program to display 5th and 6th mathematical tables


by creating two threads.

class FifthTable extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("5 *"+i+" = "+(5*i));
}
}
}

class SixthTable extends Thread


{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("6 *"+i+" = "+(6*i));
}
}
}

class demo4
{
public static void main(String args[])
{
FifthTable f=new FifthTable();
SixthTable s=new SixthTable();
f.start();
s.start();
}
}

Thread priorities
An integer value that specify relative priority of one thread to another.
Among the threads of equal priority, JRE (Thread shedular) may schedule threads in
any order for execution.
Methods:
setPriority(int priority)
int getPriority()
Priority value ranges from 0(low) to 10(high).
Normal priority is 5.
These are represeted by final static variables in Thread class
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY

Thread schedular may give preference to high priority threads while scheduling
threads for execution.
Thread priorities are only to influence the thread schedular.
Can't rely on them.

Example_Program: To demonstrate Thread Priorities.

class demo5 extends Thread


{
public void run()
{
System.out.println("child thread priority"+Thread.currentThread().getPriority());

for(int i=0;i<10;i++)
System.out.print("\nchild thread "+i);
}

public static void main(String[] args)


{
demo5 t1 = new demo5();
t1.setPriority(10);
t1.start();

System.out.println(Thread.currentThread().getPriority());
for(int i=0;i<1000;i++)
System.out.print("\nMain thread "+i);
}
}

Context switching
A thread can voluntarily relinquish control.
A thread can be preempted by a higher priority thread.

yield()
Pauses the currently executing thread temporarily for giving a chance to the
remaining threads of the same priority to execute.
If there is no waiting thread or all other waiting threads have a lower priority then the
same thread will continue its execution.
The yielded thread when it will get the chance for execution is decided by the thread
scheduler.

Example_Program : program to demonstrate yield() method.


class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread "+i);
if(i==5)
Thread.yield();
}
}
}

class demo7
{
public static void main(String args[])
{
MyThread m=new MyThread();
m.start();
for(int i=0;i<100;i++)
{
System.out.println("Main Thread "+i);
}
}
}

Other thread methods

isAlive() : helps us to know whether the thread has finished its execution or not.

join() : makes the the caller thread to wait until the thread on which join() has
invoked completes it execution.

Example_Program : program to demonstrate join() method.

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread");
try
{
Thread.sleep(500);
}
catch(InterruptedException ie)
{
System.out.println(e);
}
}
}
}
class demo6
{
public static void main(String args[]) throws InterruptedException
{
MyThread t=new MyThread();
t.start();
t.join();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}

Example_Program : creating a thread by making main clas to extend


from Thread class.

class demo20 extends Thread


{
public void run()
{
System.out.print("running");
}
public static void main(String[] args)
{
new demo20().start();
}
}
Example_ Program : Creaing thread using inner classes.
class demo21
{
public static void main(String[] args)
{
Runnable r=new Runnable()
{
public void run()
{ System.out.println("running");}
};
Thread t=new Thread(r);
t.start();
}
}

synchronization
Wihen two or more threads needs access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization.

Monitor

Key to synchronization is the concept of monitor.


A monitor is an object that is used as a mutually exclusive lock.
Only one thread can own an object's monitor at a given time.

When a thread acquires a lock, it is said to have entered the monitor.


All other threads attempting to enter the locked monitor will be suspended until the
first thread exits the monitor.
All object have implicit monitor.

How to synchronize

We can synchronize a shared resource in two ways


1. synchronized methods.
2. synchronized block.
(synchronized statement)

Method synchronization
Whichever the methods of the resource(object) you want to synchronize, decalare
those methods with synchronized modifier.
All objects have implicit monitor.
To enter an objects monitor, just call any synchronized method.

Note:

While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same object have to wait.

Example_Program : Program where two threads processes the same


resource (unsynchronized process).

class Display
{
public void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}

System.out.println(name);

}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}

public void run()


{
d.wish(name);
}
}
class demo9
{
public static void main(String args[])
{
Display d=new Display();
Mythread t1= new Mythread(d,"RAM");
Mythread t2= new Mythread(d,"LAXMAN");
t1.start();
t2.start();
}
}

Example_Program : To demonstrate synchronized methods.

class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}

System.out.print(name);
System.out.println();

}
}
}
class Mythread extends Thread
{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}

public void run()


{
d.wish(name);
}
}
class demo10
{
public static void main(String args[])
{
Display d=new Display();
Mythread t1= new Mythread(d,"RAM");
Mythread t2= new Mythread(d,"LAXMAN");
t1.start();
t2.start();
}
}

Synchronized block
If you want to synchronize access to objects of a class that was not designed for
multithreaded access (that is the class does not use snchronzed methods).
If the class was created by a third party, we do not have access to the code.
Then we can acquire lock on the object with synchronized block.

syntax

synchronized(target_instance)
{
target_instance.method1();
}
Example_Program : Synchronized block example.
class Display
{
public void wish(String name)
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.print("Good morning : ");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
System.out.print(name);
System.out.println();
}
}
}
}

class Mythread extends Thread


{
Display d;
String name;
Mythread(Display d,String name)
{
this.d=d;
this.name=name;
}

public void run()


{
d.wish(name);
}
}
class demo11
{
public static void main(String args[])
{
Display d=new Display();
Mythread t1= new Mythread(d,"RAM");
Mythread t2= new Mythread(d,"LAXMAN");
t1.start();
t2.start();
}
}

Class level locking


Class level locking prevents multiple threads to enter in synchronized block in any of
all available instances on runtime.
This means if in runtime there are 100 instances of a Class, then only one thread will
be able to execute that code in any one of instance at a time, and all other instances
will be locked for other threads.
This should always be done to make static data thread safe.

Class level locking-Example 1

public class DemoClass


{
public void demoMethod()
{
synchronized (DemoClass.class)
{
//other thread safe code
}
}
}

static synchronized methods-Example 2

public class DemoClass


{
public synchronized static void demoMethod(){}
}

Static synchronized methods will lock the class instead of object.

Note:
Static and non static synchronized methods will not block each other (ie they can run
at the same time from different threads since they acquire lock on different things).

Inter Thread communication

public final void wait() throws InterruptedException


public final void wait(long timeout) throws InterruptedException

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.

public final void notify()

Wakes up a single thread that is waiting on this object's monitor.


If many 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
public final void notifyAll()

wakes up all the threads that are waiting on this object's monitor.
One of the thread will be granted access by the Thread Schedular.
These three methods are not from Thread class, these are from Object class.

Note:

1) There exists a very rare possibility that the waiting thread resumes without
notify(). (for no apparent reason)
Oracle recommends that calls to wait() should take place with in a loop that checks
the condition on which the thread is waiting.

2) IllegalMonitorStateException
Thrown to indicate that a thread has attempted to wait on an object's monitor Or to
notify other threads waiting on an object's monitor without owning the specified
monitor.

3) You must call the wait(), notify() or notifyAll() from a synchronized context.

Example_Program : This program is used to show the inter thread


communication.

class Buffer
{
int a;
boolean produced = false;

public synchronized void produce(int x)


{

if(produced)
{
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();
}

public synchronized void consume()


{
if(!produced)
{
System.out.println("Consumer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
System.out.println("Product" + a + " is consumed.");
produced = false;
notify();
}
}

class Producer extends Thread


{
Buffer b;
public Producer(Buffer b)
{
this.b = b;
}
public void run()
{
System.out.println("Producer start producing...");
for(int i = 1; i <= 10; i++)
{
b.produce(i);
}
}
}

class Consumer extends Thread{


Buffer b;
public Consumer(Buffer b){
this.b = b;
}
public void run()
{
System.out.println("Consumer start synchronized consuming...");
for(int i = 1; i <= 10; i++)
{
b.consume();
}
}
}

public class demo12


{
public static void main(String args[])
{
//Create Buffer object.
Buffer b = new Buffer();
//creating producer thread.
Producer p = new Producer(b);
//creating consumer thread.
Consumer c = new Consumer(b);
//starting threads.
p.start();
c.start();
}

You might also like