CH-4 Java_notes
CH-4 Java_notes
_________________________________________________________________
Error
Types of Errors: -
Page 1
Trying to store value into an array of an incompatible class or type
Passing parameter that is not in a valid range or value for method
Trying to illegally change status of thread
Attempting to use a negative size for an array
Converting invalid string to a number
Accessing character that is out of bound of a string
Exception
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the
execution of a program i.e at run time, that disrupts the normal flow of the
program’s instructions.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should
not try to catch.
Exception: Exception indicates conditions that a reasonable application might
try to catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which
is base class of hierarchy. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.Another
branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError
is an example of such an error.
Page 2
1.1 Types of exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions
as the compiler checks them during compilation to see whether the programmer
has handled them or not. If these exceptions are not handled/declared in the
program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
Unchecked Exceptions
Page 3
a throws clause. Any code that absolutely must be executed after a try block
completes is put in a finally block.
Page 4
Syntax:
Type method-name (parameter list) throws exception list
{
// body of method
}
e.g.
public static void main (String a[]) throws IOException
{
----
}
OR
Example:
class DemoException
{
public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println(“answer=”+c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
}
}
Page 5
public class test
{
public static void main(String a[]) throws IOException
{
int n1=10;
int n2=10;
if (n1>n2)
throw new Exception("No.1 is greater");
else
System.out.println("No.2 is greater");
}
}
finally clause
A finally keyword is used to create a block of code that follows a try block. A
finally block of code is always executed whether an exception has occurred or
not. Using a finally block, it lets you run any cleanup type statements that you
want to execute, no matter what happens in the protected code. A finally block
appears at the end of catch block.
Page 6
Example finally Block
In this example, we are using finally block along with try block. This program
throws an exception and due to exception, program terminates its execution but
see code written inside the finally block executed. It is because of nature of
finally block that guarantees to execute the code.
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Out of try
Exception in thread main java. Lang. exception array Index out of bound
exception.
You can see in above example even if exception is thrown by the program, which
is not handled by catch block, still finally block will get executed.
finally block executes in all the scenario whether exception is caught or not. In
previous example, we use finally where exception was not caught but here
exception is caught and finally is used with handler.
class Demo
{
public static void main(String[] args)
{
int a[] = new int[2];
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
Page 7
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Exception caught
import java.lang.*;
public class testfinally
{
public static void main(String a[]) throws IOException
{
System.out.println(""Start of execution)
int a, b, c;
try
{
a=Interger.parseInt(arg[0]);
a=Interger.parseInt(arg[1]);
c=a/b;
System.out.println("Answer is"+c);
}
catch(Exception e)
{
System.out.println(e)
}
finally
{
System.out.println("Finally will always execute");
}
Page 8
System.out.println("Execution complete here");
}
}
Throw Throws
Whenever we want to force an when we know that a particular
exception then we use throw exception may be thrown or to pass a
keyword. possible exception then we use
throws keyword.
"Throw" is used to handle user- JVM handles the exceptions which are
defined exception. specified by "throws".
It can also pass a custom message to Point to note here is that the Java
your exception handling module. compiler very well knows about the
exceptions thrown by some methods
so it insists us to handle them.
Throw keyword can also be used to We can also use throws clause on
pass a custom message to the the surrounding method instead of
exception handling module i.e. the try and catch exception handler.
message which we want to be
printed.
Throw is used to actually throw the Whereas throws is declarative for the
exception. method. They are not
interchangeable.
Page 9
It is used to generate an exception. It is used to forward an exception.
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax: Syntax:
throw is followed by an object throws is followed by a class
(new type) and used with the method
used inside the method signature
Built-in Exception
Java exceptions are the exceptions that are caused by run time error in the
program. Some common exceptions in java are as follows:
Sr. Built-in Exception Explaination
No.
1 ArithmeticException It is caused by Maths error sush as
divide by 0.
2 ArrayIndexOutOfBoundsException It is caused when array index is out of
bound
3 ArrayStoreException It is caused when a program tries to
store wrong type of data in an array.
4 FileNotFoundException It is caused by an attempt to access a
non-existent file.
5 IOException It is caused by general IO failure such
as inability to read from the file.
6 NullPointerException It is caused by referencing a null object
Nested Try
The nested try is used to implement multiple try statements in a single block of
main method.
Syntax: -
Try
{
----
----
Try
{
----
----
}
}
Example:
class nested_try_block
{
public static void main(String[] args)
{
try
{
int arr[]={5,0,1,2};
try
{
int x = arr[3]/arr[1]; //2/0
}
catch(ArithmeticException ae)
{
System.out.println(" You can not divide by zero");
}
Page 11
arr[8]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
}
}
Chained Exception
Whenever in a program first exception causes another exception to occur it
is called a chained exception.
Exception chaining is also known as nesting exception and it is technique
for handling the exception which occurs one after the other that is most of
the time given by an application in response to an exception by throwing
another exception.
Typically, the second exception caused by the first exception therefore
chained exception helped programmer to know when one exception causes
another.
The methods and constructor in throwable that support chain exception.
Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when
an integer is divided by zero.
class Example1
{
public static void main(String args[])
{
try{
Page 12
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:
Class: Java.lang.ArrayIndexOutOfBoundsException
This exception occurs when you try to access the array index which does not
exist. For example, If array is having only 5 elements and we are trying to display
7th element then it would throw this exception.
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0
to 9. Since we are try to access element of index 11, the program is throwing this
exception.
Class: Java.lang.NumberFormatException
Page 13
For example, the statement int num=Integer.parseInt ("XYZ"); would
throw NumberFormatException because String “XYZ” cannot be parsed to int.
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:
Class: Java.lang.StringIndexOutOfBoundsException
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
13
StringIndexOutOfBoundsException!!
Page 14
Exception occurred because the referenced index was not present in the String.
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
Here, length() is the function, which should be used on an object. However in the
above example String object str is null so it is not an object due to
which NullPointerException occurred.
Example:
System.out.println(obj.division(15,0));
}
}
Example:
Example:
import java.io.*;
class MyOwnException extends Exception
{
public MyOwnException(String msg)
{
super(msg);
}
}
class EmployeeTest
{
public static void main(String[] args) throws IOException
Page 16
{
DataInputStream d=new DataInputStream(System.in);
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
}
/* catch (IOException e)
{
e.printStackTrace();
} */
}
}
Example:
import java.io.*;
class MyOwnException extends Exception
{
public MyOwnException(String msg)
{
super(msg);
}
}
class EmployeeTest
{
Page 17
public static void main(String[] args) throws IOException
{
DataInputStream d=new DataInputStream(System.in);
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
}
/* catch (IOException e)
{
e.printStackTrace();
} */
}
}
class posex
{
public static void main(String args[])
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
Page 18
int n;
try
{
System.out.println("Enter any Number");
n=Integer.parseInt(bf.readLine());
if(n>0)
{
System.out.println(“You are Entered Positive Number, please entered Negative
number for exception ");
}
else
{
throw new PException("Entered Number is Negative Number");
}
}
catch(PException e)
{System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);}
}
}
Output:
Enter any Number 3
You are Entered Positive Number, please entered Negative number for exception
Enter any Number -3
PException: Entered Number is Negative Number
class passwordau
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s1=new String();
String s2=new String();
try
{
Page 19
System.out.println("Enter to set the password");
s1=d.readLine();
System.out.println("Re-Enter the password");
s2=d.readLine();
if(s1.equals(s2))
{
System.out.println("Password Validated");
}
else
{
throw new MyException("Authentication Failure");
}
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter to set the password abc
Re-Enter the password abc
Password Validated
Enter to set the password abc
Re-Enter the password xyz
MyException: Authentication Failure
class oddeven
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
int n;
Page 20
try
{
System.out.println("Enter a Number");
n=Integer.parseInt(d.readLine());
if(n%2==0)
{
throw new MyException("Number is EVEN");
}
else
{
throw new MyException("Number is ODD");
}
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter a Number 2
MyException: Number is EVEN
Enter a Number 3
MyException: Number is ODD
Program to accept a string from the user and throw an exception if the
string is not containing character 'a'.
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class StringB
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s;
try
Page 21
{
int len;
char ch;
System.out.println("Enter the String");
s=d.readLine();
if(s.indexOf("a")!=-1)
{
System.out.println("Your String contains 'a'");
}
else
{
throw new MyException("Your String does not contains 'a'");
}
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter the String java
Your String contains 'a'
Enter the String ops
MyException: Your String does not contains 'a'
Page 22
System.out.println("Enter String one and String two ");
s1=br.readLine();
s2=br.readLine();
if(s1.equalsIgnoreCase(s2)) // any similar method which give
correct result
{
System.out.println("String Matched");
}
else
{
throw new MyException("String Mismatch Exception");
}
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Page 23
catch(myException e)
{
System.out.println(e.getMessage());
}
catch(IOException ie)
{}
}
}
class test
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter E-mail Address: ");
String s1=bin.readLine();
char c='@';
if(s1.contains("@"))
{
System.out.println("ValidEmail ");
}
else
{
throw new myException("InvalidEmailException");
}
}
catch(myException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Page 24
Output:
Program to accept string from a user, if its length is less than 6, then
throw user defined exception “Invalid String” otherwise display the
string in uppercase
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class test
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s1=new String();
try
{
System.out.println("Enter String");
s1=d.readLine();
int n=6;
if(s1.length() >= n)
{
System.out.println(s1.toUpperCase());
}
else
{
throw new MyException("Invalid String");
}
}
catch(MyException e)
Page 25
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
C:\Java\jdk1.7\bin>java test
Enter String
hello
MyException: Invalid String
C:\Java\jdk1.7\bin>java test
Enter String
computer
COMPUTER
Java Program that contains a class Account with acc_no, name and
balance as field. Accept(), withdraw(), deposite() as methods. If
balance<500 then raise exception “MinimumBalanceException”. If name
contains digits then raise exception ”invalidNameException”.
Sol:
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class test
{
int balance;
int amount;
void accept(String s)
{
String s1="Hello";
String s2;
try
{
s2=s;
if(s1.equals(s2))
{
System.out.println("Valid Name");
}
else
Page 26
{
throw new MyException("InvalidNameException");
}
}
catch(MyException e)
{
System.out.println(e);
}
} //End of accept method
void deposit(int n)
{
amount=n;
balance=balance+amount;
System.out.println("Total Balance="+balance);
} //end of deposit
void withdraw(int w)
{
amount=w;
try
{
balance=balance-amount;
if(balance<=500)
{
throw new MyException("MinumumBalanceException");
}
else
{
System.out.println("Balance="+balance);
}
}
catch(MyException e)
{
System.out.println(e);
}
} //end of withdraw
Page 27
Create a class student with attributes rno, name , age and class.
Initialize values through parameterize constructor. If age of student is
not in between 15 to 21 then generate user defined exception as
“InvalidAgeException”. Similarly if name contains special symbols or
digits then raise exception as “InvalidNameException”. Handle these
exceptions.
class InvalidAgeException extends Exception{}
class InvalidNameException extends Exception{}
class Student
{
int RollNo, Age;
String Name,Course;
Student(int rno, String name, int age, String course)
{
try
{
RollNo = rno;
Name = name;
Age = age;
Course = course;
if(Age<15 || Age>21)
throw new InvalidAgeException();
for(int i=0; i<Name.length(); i++)
if(Character.isDigit(Name.charAt(i)))
throw new InvalidNameException();
}
catch(InvalidAgeException e)
{
System.out.println("Age Not Within The Range");
}
catch(InvalidNameException e)
{
System.out.println("Name not valid");
}
}
public String toString()
{
return "Roll No:"+RollNo+
"\nName :"+Name+
Page 28
"\nAge :"+Age+
"\nCourse :"+Course;
}
}
class StudentExceptionDemo
{
public static void main(String args[])
{
Student s1 = new Student(1,"Ram",17,"Java Programming");
System.out.println(s1);
Student s2 = new Student(2,"John",28,"C++ Programming");
System.out.println(s2);
Student s3 = new Student(3,"Akbar15",19,"C++ Programming");
System.out.println(s3);
}
}
Output:
Roll No:1
Name :Ram
Age :17
Course :Java Programming
Age Not Within The Range
Roll No:2
Name :John
Age :28
Course :C++ Programming
Name not valid
Roll No:3
Name :Akbar15
Age :19
Course :C++ Programming
Multithreading Programming
Page 29
Thread
Thread is a smallest unit of executable code or a single task is also called
as thread.
Each tread has its own local variable, program counter and lifetime.
A thread is similar to program that has a single flow of control.
It has beginning, body and end executes command sequentially.
Page 30
Thread Life Cycle Thread has five different states throughout its life.
1) Newborn State
When a thread object is created it is said to be in a new born state. When
the thread is in a new born state it is not scheduled running from this state
it can be scheduled for running by start() or killed by stop(). If put in a
queue it moves to runnable state.
A NEW Thread (or a Born Thread) is a thread that's been created but not yet
started. It remains in this state until we start it using the start() method.
The following code snippet shows a newly created thread that's in the NEW state:
Runnable runnable = new NewState();
Thread t = new Thread(runnable);
2) Runnable State
It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is
waiting for execution. If all threads have equal priority, then they are given
time slots for execution in round robin fashion. The thread that relinquishes
control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
Page 31
Runnable runnable = new NewState();
Thread t = new Thread(runnable); t.start();
3) Running State
It means that the processor has given its time to the thread for execution.
The thread runs until it relinquishes control on its own or it is pre-empted
by a higher priority thread.
4) Blocked State
A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
o suspend() : Thread can be suspended by this method. It can be
rescheduled by resume().
o wait(): If a thread requires to wait until some event occurs, it can be
done using wait method and can be scheduled to run again by
notify().
o sleep(): We can put a thread to sleep for a specified time period using
sleep(time) where time is in ms. It reenters the runnable state as
soon as period has elapsed /over.
5) Dead State
Whenever we want to stop a thread form running further we can call its
stop(). The stop() causes the thread to move to a dead state. A thread will
also move to dead state automatically when it reaches to end of the
method. The stop method may be used when the premature death is
required
New/Start:
This is the state the thread is in after the Thread instance has been created, but the
start() method has not been invoked on the thread. It is a live Thread object, but not
yet a thread of execution. At this point, the thread is considered not alive.
Runnable:
This means that a thread can be run when the time-slicing mechanism has CPU
cycles available for the thread. Thus, the thread might or might not be running at any
Page 32
moment, but there’s nothing to prevent it from being run if the scheduler can arrange
it. That is, it’s not dead or blocked.
Running:
This state is important state where the action is. This is the state a thread is in when
the thread scheduler selects it (from the runnable pool) to be the currently executing
process. A thread can transition out of a running state for several reasons, including
because "the thread scheduler felt like it". There are several ways to get to the
runnable state, but only one way to get to the running state: the scheduler chooses a
thread from the runnable pool of thread.
Blocked:
The thread can be run, but something prevents it. While a thread is in the blocked
state, the scheduler will simply skip it and not give it any CPU time. Until a thread
reenters the runnable state, it won’t perform any operations. Blocked state has some
sub-states as below,
Blocked on I/O: The thread waits for completion of blocking operation. A thread can enter this
state because of waiting I/O resource. In that case, the thread sends back to runnable state after
the availability of resources.
Blocked for join completion: The thread can come in this state because of waiting for the
completion of another thread.
Blocked for lock acquisition: The thread can come in this state because of waiting for acquire
the lock of an object.
Dead:
A thread in the dead or terminated state is no longer schedulable and will not receive
any CPU time. Its task is completed, and it is no longer runnable. One way for a task
to die is by returning from its run( ) method, but a task’s thread can also be
interrupted, as you’ll see shortly.
Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.
Page 33
With proper syntax and example explain following thread methods:
2) resume() syntax : public void resume() This method resumes a thread which
was suspended using suspend() method.The thread enter in active state i.e
Runnable state.
3) yield() syntax : public static void yield() The yield() method causes the
currently executing thread object to temporarily pause and move to runnable
state from running state and allow other threads to execute.
4) wait() and notify() syntax : public final void wait() This method causes the
current thread to wait until some event occurs and another thread invokes the
notify() method or the notifyAll() method for this object.
5) stop() syntax: void stop() Used to kill the thread. It stops thread.
Page 34
using sleep(time) where time is in ms. It reenters the runnable state as soon as
period has elapsed /over.
Eg.
class sus extends Thread implements Runnable
{
static Thread th;
float rad,r;
public sus()
{
th= new Thread();
th.start();
}
public void op()
{
System.out.println("\nThis is OP");
if(rad==0)
{
System.out.println("Waiting for input radius");
Try
{
wait();
}
catch(Exception ex)
{
}
}
}
public void ip()
{
System.out.println("\nThis is IP");
r=7;
rad= r;
Page 35
System.out.println(rad);
System.out.println("Area = "+3.14*rad*rad);
notify();
}
public static void main(String arp[])
{
Try
{
sus s1 = new sus();
System.out.println("\nReady to go");
Thread.sleep(2000);
System.out.println("\nI am resuming");
th.suspend();
Thread.sleep(2000);
th.resume();
System.out.println("\nI am resumed once again");
s1.op();
s1.ip();
s1.op();
}
catch(Exception e)
{
}
}
}
Page 36
public static int NORM_PRIORITY: This is default priority of a thread if
do not explicitly define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread.
Value for this is 10.
Get and Set Thread Priority:
1. public final int getPriority(): java.lang.Thread.getPriority() method
returns priority of given thread.
2. public final void setPriority(int
newPriority): java.lang.Thread.setPriority() method changes the
priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.
Creating Threads
There are two ways to create threads in java:
1. By extending thread class
o User specified thread class is created by extending the class ‘Thread’
and overriding its run() method.
o For creating a thread a class has to extends the thread class that is
java.lang.Thread
o Syntax: -
Declare class as extending thread
class Mythread extends Thread
{
____
------
}
Page 37
1.1.2 Run Method Syntax:
class MyThreadDemo_interface
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Develop a program to create two threads such that one thread will
print odd no. and another thread will print even no. between 1-20
Page 38
class odd extends Thread
{
public void run()
{
for(int i=1;i<=20;i=i+2)
{
System.out.println("ODD="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=20;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
Page 39
}
}
class oddeven2
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();
o.start();
e.start();
}
}
Develop a program to create three threads such that one thread will
print odd no. and another thread will print even no. and third thread
will print all no. between 1-10 and set Priority.
class odd extends Thread
{
public void run()
{
for(int i=1;i<=10;i=i+2)
{
System.out.println("ODD="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
Page 40
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=10;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class allnumbers extends Thread
{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println("All numbers="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
Page 41
}
}
}
}
class oddeven1
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();
allnumbers a=new allnumbers();
o.setPriority(6);
e.setPriority(4);
a.setPriority(8);
o.start();
e.start();
a.start();
}
}
Write a program to create two threads; one to print numbers in original
order and other to reverse order from 1 to 50.
Page 42
catch(Exception e)
{}
}
}
class reverse extends Thread
{
public void run()
{
try
{
for(int i=50; i>=1;i--)
{
System.out.println("\t Second Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e)
{
}
}
}
class orgrev
{
public static void main(String args[])
{
new original().start();
new reverse().start();
System.out.println("Exit from Main");
}
}
Page 43
import java.lang.*;
class even extends Thread
{
public void run()
{
try
{
for(int i=0;i<=10;i=i+2)
{
System.out.println("\tEven thread="+i);
Thread.sleep(300);
}
}
catch(InterruptedException e)
{}
}
}
Page 44
class evenodd
{
public static void main(String args[])
{
new even().start();
new odd().start();
System.out.println("Exit from main");
}
}
o When the thread gets a chance to execute, its target run() method will run.
For E.g.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Page 45
using Runnable Interface
When two or more threads need 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.
Synchronization used when we want to –
1) prevent data corruption.
2) prevent thread interference.
3) Maintain consistency If multiple threads require an access to an
Object.
Page 46
Program based on synchronization:
class Callme
{
void call(String msg)
{
System.out.print("[" +msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
Page 47
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
try
{
ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
Thread Priority
Threads in java are sub programs of main application program and share
the same memory space. They are known as light weight threads.
A java program requires at least one thread called as main thread. The
main thread is actually the main method module which is designed to
create and start other threads.
A Thread is similar to a program that has a single flow of control. Every
thread has a beginning, a body and an end.
Page 48
However, thread is not a program, but runs within a program.
Thread Priority: In java each thread is assigned a priority which affects
the order in which it is scheduled for running. Threads of same priority are
given equal treatment by the java scheduler.
The thread class defines several priority constants as: -
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Thread priorities can take value from 1-10.
1) setPriority () This method is used to assign new priority to the
thread
Syntax: Thread.setPriority (priority value);
2) getPriority() It obtain the priority of the thread and returns integer
value.
Syntax: int Thread.getPriority ();
Intercrosses Communication
wait() tells calling thread to give up monitor and go to sleep until some other
thread enters the same monitor and call notify.
notify() wakes up a thread that called wait() on same object.
notifyAll() wakes up all the thread that called wait() on same object.
import java.util.Scanner;
public class threadexample
{
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Page 49
// Create a thread object that calls pc.produce()
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
};
// t1 finishes before t2
t1.join();
t2.join();
}
Page 50
public void produce()throws InterruptedException
{
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
System.out.println("producer thread running");
// Sleeps for some time and waits for a key press. After key
// is pressed, it notifies produce().
public void consume()throws InterruptedException
{
// this makes the produce thread to run first.
Thread.sleep(1000);
Scanner s = new Scanner(System.in);
// Sleep
Thread.sleep(2000);
}
}
}
}
Page 51
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
Deadlock
Page 52
Deadlock is a situation of complete Lock, when no thread can complete its
execution because lack of resources.
In the diagram, Thread 1 is holding a resource R1, and need another
resource R2 to finish execution, but R2 is locked by Thread 2, which needs
R3, which in turn is locked by Thread 3.
Hence none of them can finish and are stuck in a deadlock.
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
Page 53
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Page 54