CH-4 Java_notes
CH-4 Java_notes
_________________________________________________________________
Error
Types of Errors: -
2. Runtime errors
errors are known as compile time errors. The most of common problems are:
Missing semicolon
Missing (or mismatch of) bracket in classes & methods
Misspelling of identifiers & keywords
Sometimes a program may compile successfully creating the .class file but may not run
properly. Such programs may produce wrong results due to wrong logic or may
terminate due to errors such as stack overflow. When such errors are encountered java
typically generates an error message and aborts the program. The most common run-
Page 1
Dividing an integer by zero
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.
An exception is an event, which occurs during the execution of a program, that stop
the flow of the program's instructions and takes appropriate actions if handled.
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)
Page 2
to indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
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
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled
them or not but it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
1. try: This block applies a monitor on the statements written inside it. If there exist any
exception, the control is transferred to catch or finally block.
Syntax:
try
{
// block of code to monitor for errors
2. catch: This block includes the actions to be taken if a particular exception occurs.
Syntax:
catch (ExceptionType1 exOb)
}
3. finally: finally block includes the statements which are to be executed in any case, in
Syntax:
finally
{
4. throw: This keyword is generally used in case of user defined exception, to forcefully
raise the exception and take the required action.
Syntax:
Page 4
5. throws: throws keyword can be used along with the method definition to name the
list of exceptions which are likely to happen during the execution of that method. In
// body of method
}
e.g.
{
----
}
OR
Example:
class DemoException
{
try
{
int b=8;
int c=b/0;
System.out.println(“answer=”+c);
}
catch(ArithmeticException e)
Page 5
System.out.println(“Division by Zero”);
}
}
import java.lang.*;
public class test
{
int n1=10;
int n2=10;
if (n1>n2)
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.");
}
}
Page 7
}
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 */
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Exception caught
Page 8
import java.lang.*;
{
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
{
Page 9
Throw Throws
"Throw" is used to handle user-defined JVM handles the exceptions which are
It can also pass a custom message to your Point to note here is that the Java compiler
handle them.
Throw keyword can also be used to pass a We can also use throws clause on the
custom message to the exception handling surrounding method instead of try and
be printed.
Throw is used to through exception system Throws is used for to throws exception
Throw is used to actually throw the Whereas throws is declarative for the
Page 10
Built-in Exception
Java exceptions are the exceptions that are caused by run time error in the program.
0.
existent file.
setting.
Nested Try
Page 11
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
{
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 12
arr[8]=3;
catch(ArrayIndexOutOfBoundsException e)
{
}
}
Chained Exception
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
Typically, the second exception caused by the first exception therefore chained
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
{
Page 13
public static void main(String args[])
{
try{
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.
Page 14
Example 3: NumberFormat Exception
Class: Java.lang.NumberFormatException
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
An object of this class gets created whenever an index is invoked of a string, which is
not in the range.
Each character of a string object is stored in a particular index starting from 0.
To get a character present in a particular index of a string we can use a method
charAt(int) of java.lang.String where int argument is the index.
E.g
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
Page 15
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:
13
StringIndexOutOfBoundsException!!
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:
Page 16
public class throws_Example1
{
int division(int a, int b) throws ArithmeticException
{
int t = a/b;
return t;
}
public static void main(String args[])
{
throws_Example1 obj = new throws_Example1();
System.out.println(obj.division(15,0));
}
}
Example:
{
static void checkEligibilty(int stuage, int stuweight)
{
throw new ArithmeticException("Student is not eligible for registration");
}
else
{
System.out.println("Student Entry is Valid!!");
checkEligibilty(10, 35);
System.out.println("Have a nice day..");
Page 17
}
Example:
import java.io.*;
{
public MyOwnException(String msg)
super(msg);
}
}
class EmployeeTest
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
else
System.out.println("Input is valid!!");
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
/* catch (IOException e)
Page 18
{
e.printStackTrace();
} */
}
Example:
import java.io.*;
super(msg);
}
class EmployeeTest
{
public static void main(String[] args) throws IOException
try
{ System.out.println("Enter age:");
int a=Integer.parseInt(d.readLine());
if(a < 0)
System.out.println("Input is valid!!");
Page 19
catch (MyOwnException e)
{ e.printStackTrace();
//System.out.println("Error");
}
/* catch (IOException e)
{
e.printStackTrace();
} */
Program to throw user defined exception by accepting a number from user and throw
an exception if the number is not positive number.
import java.lang.*;
import java.io.*;
class PException extends Exception
{
PException(String msg)
{
super(msg);
}
}
class posex
{
public static void main(String args[])
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
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 ");
}
Page 20
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
Program to accept a password from the user and throw 'authentication Failure'
exception if the password is incorrect.
import java.io.*;
import java.lang.*;
/class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class passwordau
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s1=new String();
String s2=new String();
try
{
System.out.println("Enter to set the password");
s1=d.readLine();
System.out.println("Re-Enter the password");
s2=d.readLine();
Page 21
if(s1.equals(s2))
{
System.out.println("Password Validated");
}
else
{
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
Enter to set the password abc7
Re-Enter the password abc
Password Validated
Enter to set the password abc
Re-Enter the password xyz
MyException: Authentication Failure
Program to accept a number from the user and throw an exception if the number is not
an even number.
import java.io.*;
import java.lang.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class oddeven
{
public static void main(String args[])
Page 22
{
DataInputStream d=new DataInputStream(System.in);
int n;
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);
Page 23
}
}
class StringB
{
public static void main(String args[])
{
DataInputStream d=new DataInputStream(System.in);
String s;
try
{
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'
Write a program to throw a user defined exception “String Mismatch Exception” if two
strings are not equal. (ignore case).
import java.io.*;
Page 24
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class ExceptionTest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
String s1,s2;
try
{
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);
}
}
}
Write a program to throw a user defined exception as ‘Invalid Age’, if age entered by
the user is less than eighteen. Also mention any two common java exceptions and their
cause.
import java.lang.Exception;
import java.io.*;
Page 25
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}
class agetest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("enter the age : ");
int n=Integer.parseInt(br.readLine());
if(n < 18 )
throw new myException("Invalid Age");
else
System.out.println("Valid age");
}
catch(myException e)
{
System.out.println(e.getMessage());
}
catch(IOException ie)
{}
}
}
Write a java program to accept email address of a user and throw a user defined
exception InvalidEmailException if it starts with digit or does not contain @ symbol.
import java.io.*;
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}
class test
{
public static void main(String args[])
Page 26
{
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);
}
}
}
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.*;
Page 27
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)
{
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
Page 28
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
{
throw new MyException("InvalidNameException");
}
}
catch(MyException e)
{
System.out.println(e);
}
Page 29
} //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 30
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");
}
}
Page 31
public String toString()
{
return "Roll No:"+RollNo+
"\nName :"+Name+
"\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
It allows process to run its task in parallel mode on single processor system.
Page 32
In multithreading concept several multiple light weight processes run in a single
For e.g. When work with word processor you can perform many different task such as
printing, spell check and so on. Multithreading software treats each process as a
separate program.
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.
Page 33
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.
Page 34
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().
3) Running State
It means that the processor has given its time to the thread for execution. The thread
thread.
4) Blocked State
A thread can be temporarily suspended or blocked from entering into the runnable
resume().
o wait(): If a thread requires to wait until some event occurs, it can be done using
Page 35
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
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
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,
Page 36
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
1) suspend() - syntax : public void suspend() This method puts a thread in suspended
Page 37
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
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
5) stop() syntax: void stop() Used to kill the thread. It stops thread.
6)sleep() syntax: public static void sleep(long millis) throws InterruptedException We can
put a thread to sleep for a specified time period using sleep(time) where time is in ms. It
Eg.
class sus extends Thread implements Runnable
float rad,r;
public sus()
Page 38
th.start();
System.out.println("\nThis is OP");
if(rad==0)
{
System.out.println("Waiting for input radius");
Try
wait();
}
catch(Exception ex)
System.out.println("\nThis is IP");
r=7;
rad= r;
System.out.println(rad);
System.out.println("Area = "+3.14*rad*rad);
notify();
}
public static void main(String arp[])
Try
Page 39
{
System.out.println("\nReady to go");
Thread.sleep(2000);
System.out.println("\nI am resuming");
th.suspend();
Thread.sleep(2000);
th.resume();
s1.op();
s1.ip();
s1.op();
}
catch(Exception e)
{
}
Creating Threads
o For creating a thread a class has to extends the thread class that is
java.lang.Thread
o Syntax: -
{
____
------
The easiest way to create a thread is to create a class that implements the
runnable interface. After implementing runnable interface, the class needs
to implement the run() method.
run() method can call other methods, can use other classes and
declare variables just like any other normal method.
class MyThreadDemo_interface
{
t.start();
Develop a program to create two threads such that one thread will print odd no. and
Page 42
{
{
for(int i=1;i<=20;i=i+2)
System.out.println("ODD="+i);
try
{
sleep(1000);
catch(Exception e)
{
System.out.println("Error");
}
}
{
public void run()
for(int i=0;i<=20;i=i+2)
{
System.out.println("EVEN="+i);
try
sleep(1000);
}
catch(Exception e)
Page 43
System.out.println("Error");
}
}
class oddeven2
{
public static void main(String arg[])
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
for(int i=1;i<=10;i=i+2)
System.out.println("ODD="+i);
try
Page 44
sleep(1000);
catch(Exception e)
{
System.out.println("Error");
}
}
{
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
Page 45
{
for(int i=0;i<=10;i++)
{
System.out.println("All numbers="+i);
try
sleep(1000);
}
catch(Exception e)
System.out.println("Error");
}
}
}
class oddeven1
{
odd o=new odd();
o.setPriority(6);
e.setPriority(4);
a.setPriority(8);
o.start();
e.start();
a.start();
Page 46
Write a program to create two threads; one to print numbers in original order and
{
public void run()
try
{
for(int i=1; i<=50;i++)
Thread.sleep(300);
}
catch(Exception e)
{}
}
{
public void run()
try
{
for(int i=50; i>=1;i--)
Thread.sleep(300);
}
Page 47
}
catch(Exception e)
{
}
class orgrev
{
new original().start();
new reverse().start();
System.out.println("Exit from Main");
Q. Write a program to create two threads one to print odd numbers from 1 to 10 and
import java.lang.*;
try
{
for(int i=0;i<=10;i=i+2)
System.out.println("\tEven thread="+i);
Thread.sleep(300);
Page 48
}
catch(InterruptedException e)
{}
{
try
{
for(int i=1;i<=10;i=i+2)
{
System.out.println("\todd thread="+i);
Thread.sleep(300);
}}
catch(InterruptedException e)
{
}
class evenodd
{
new even().start();
new odd().start();
Page 49
}
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().
o When the thread gets a chance to execute, its target run() method will run.
For E.g.
System.out.println("thread is running...");
t1.start();
Page 50
public void run()
}
}
class test
{
public static void main(String args[])
{
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.
Page 51
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("]");
}
{
String msg;
Callme target;
Thread t;
target=targ;
msg=s;
t=new Thread(this);
t.start();
Page 52
{
synchronized(target)
{
target.call(msg);
class Synch
{
try
{
ob1.t.join();
ob2.t.join();
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
Thread Priority
Page 53
Threads in java are sub programs of main application program and share the same
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
which it is scheduled for running. Threads of same priority are given equal treatment
MAX_PRIORITY = 10
value.
Syntax: int Thread.getPriority ();
Intercrosses Communication
purpose. These method are implemented as final methods in Object, so that all
classes have them. All the three method can be called only from within
a synchronized context.
Page 54
wait() tells calling thread to give up monitor and go to sleep until some other thread
import java.util.Scanner;
public class threadexample
{
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Page 55
{
e.printStackTrace();
}
}
});
// t1 finishes before t2
t1.join();
t2.join();
}
// 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);
Page 56
// running at a time.
synchronized(this)
{
System.out.println("Waiting for return key.");
s.nextLine();
System.out.println("Return key pressed");
// Sleep
Thread.sleep(2000);
}
}
}
}
}
}
Page 57
t.printTable(100);
}
}
Deadlock
Deadlock is a situation of complete Lock, when no thread can complete its execution
finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked
by Thread 3.
Page 58
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
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...");
}
}
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) {}
Page 59
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Page 60