0% found this document useful (0 votes)
31 views45 pages

Unit No - 4

Uploaded by

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

Unit No - 4

Uploaded by

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

Java Programming (22412)

Unit No.4
Exception Handling and Multithreading

 CO d. Implement Exception Handling.

Error – These are not exceptions but the problems that arise beyond the control of the user
or the programmer.

Types of Errors –

 Compile Time Error – All the syntax errors given by Java Compiler are known as
Compile Time Errors.
 Missing semicolon
 Missing brackets in class or method
 Missing double quotes in String etc.
 Run Time Error – Sometimes, a program may compile successfully, but may not run
properly because of wrong logic. The errors which are generated while program is
running are known as Run Time Errors.
 Opening a file which does not exists
 Trying to store value at negative index value
 Accessing element that are out of capacity of array etc.

What is Exception?

An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.

When an error occurs within a method, the Interpreter creates an object and hands it. The object,
called an exception object, contains information about the error, including its type and the state
of the program when the error occurred. Creating an exception object and handing it to the
runtime system is called throwing an exception.

If the exception object is not handled properly then the interpreter will display an error message.

Categories of Exceptions –

 Checked Exceptions - A checked exception is an exception that is typically a user error


or a problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.

Sou.Venutai Chavan Polytechnic,Pune. 1


Java Programming (22412)

 Unchecked Exceptions – Unchecked Exceptions are the exceptions which are not
checked by the compiler at the run time of compiling program.

Exception Hierarchy:
 All exception classes are subtypes of the java.lang.Exception class.
 The exception class is a subclass of the Throwable class.
 Other than the exception class there is another subclass called Error which is derived
from the Throwable class.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

Exception Handling –

The purpose of exceptional handling is to detect & report an exception so that the proper
action can be taken & prevent the program which is automatically terminate or stop the
execution due to exception.

The exception handling mechanism performs following tasks –

 Find the problem (Hit the exception)


 Inform about the Error (Throws the exception)
 Receive the error information (Catch the exception)
 Take corrective action (Handle the exception)

Java exception handling is managed by 5 keywords –

1. try – The program statements that to be monitored for exceptions are contained within
the try block. If an exception occurs within try block then it is thrown.

Sou.Venutai Chavan Polytechnic,Pune. 2


Java Programming (22412)

2. catch – code can catch the exception & handle it in some relational manner
3. throw – System generated exceptions are automatically thrown by java run time system.
To manually throw an exception ‘throw’ keyword is used.
4. throws – any exception that is generated out of a method must be specified as ‘throws’
clause.
5. finally –any code that must be executed before a method returns is put in a finally block.

Idea of Exception Handling –

Try Block
Exception object
Statements that cause an
Throws exception creator
exception
object

Catch Block Exception Handler

Statements that handles an


exception
Syntax –

try

//statements

catch (Exception-Type1 eobj)

//statements to handle exception

____

finally

//statements }}

Sou.Venutai Chavan Polytechnic,Pune. 3


Java Programming (22412)

Program –

class exc

public static void main(String args[])

int a=10;

int b=0;

int c;

try

c=a/b;

catch (Exception eobj)

System.out.println("Error " + eobj);

Output -

C:\my>java exc

Error java.lang.ArithmeticException: / by zero

Sou.Venutai Chavan Polytechnic,Pune. 4


Java Programming (22412)

Common Java Exceptions –

Following is the list of Java Unchecked RuntimeException.

Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an unlocked
IllegalMonitorStateException
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread

Sou.Venutai Chavan Polytechnic,Pune. 5


Java Programming (22412)

state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the
CloneNotSupportedException
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Multiple Catch Block –

try block can be followed by multiple catch blocks. The syntax for multiple catch blocks are as
following:

try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{

Sou.Venutai Chavan Polytechnic,Pune. 6


Java Programming (22412)

//Catch block
}
- If an exception occurs in the protected code, the exception is thrown to the first catch
block in the list.
- If the data type of the exception thrown matches ExceptionType1, it gets caught there.
- If not, the exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call
stack.

Program –

class mexc

public static void main(String args[])

try

int a=0;

int b=10/a;

int c[]={1,2,3};

catch (ArithmeticException eobj)

System.out.println("Arithmetic Error " + eobj);

catch (ArrayIndexOutOfBoundsException eobj)

System.out.println("Array Error " + eobj);

Sou.Venutai Chavan Polytechnic,Pune. 7


Java Programming (22412)

Output –

C:\my>java mexc

Arithmetic Error java.lang.ArithmeticException: / by zero

Program 2-

class mcatch
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x = a[2]/b - a[1]; // Array Error because no element at 2nd Position
}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Data Type");
}

int y = a[1]/a[0];
System.out.println("y= "+y);
}
}
Output –

C:\my>java mcatch

Sou.Venutai Chavan Polytechnic,Pune. 8


Java Programming (22412)

Divide by Zero

y= 2

Nested Try Statement –

 A try statement can be inside the block of another try.


 Each time a try statement is entered, the context of that exception is pushed on the stack.
 If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound & next try statements catch handler are inspected for a match.

Syntax –

try
{
//statements
try
{
//statements
}
catch (Exception eobj)
{
//statements to handle exception
}
}
catch (Exception-Type1 eobj)
{
//statements to handle exception
}

Program 1 –
class nTry
{
public static void main(String args[])
{
int num1=100;
int num2=50;
int num3=50;
int r;
try
{
r = num1 / (num2-num3);
System.out.println("Result =" +r);
try{
r = num1 / (num2-num3);
Sou.Venutai Chavan Polytechnic,Pune. 9
Java Programming (22412)

System.out.println("Result =" +r);


}
catch (ArithmeticException e)
{
System.out.println("This is Arithmetic Error");
}
}
catch (ArithmeticException g)
{
System.out.println("New Arithmetic Error");
}
}
}

Output –
C:\my>java nTry
New Arithmetic Error

Program 2-
class mtry
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b= 9/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("other statement...");
}
catch (Exception e)
{
System.out.println("Handled");
}
}
}

Output –

Sou.Venutai Chavan Polytechnic,Pune. 10


Java Programming (22412)

C:\my>java mtry
going to divide
java.lang.ArithmeticException: / by zero
other statement...

The throw Keyword –

- The throw keyword is used to explicitly throw an exception


- Can throw checked & unchecked exceptions
- The throw keyword is basically used to throw custom exception
-

Program -

class ThrowE

static void validate(int age)

if (age<18)

throw new ArithmeticException("Not Valid");

else

System.out.println("You can vote");

public static void main(String args[])

validate(13);

System.out.println("rest of code");

Output –

Sou.Venutai Chavan Polytechnic,Pune. 11


Java Programming (22412)

C:\my>java ThrowE

Exception in thread "main" java.lang.ArithmeticException: Not Valid

at ThrowE.validate(ThrowE.java:6)

at ThrowE.main(ThrowE.java:13)

The throws Keywords:

- The throws keyword is used to declare an exception


- It gives information to user that there may occur an exception so provide exception
handling code

Syntax –

Void method_name() throws exception_class_name()

//code

Program –

import java.io.IOException;
class simple
{
void m() throws IOException
{
throw new IOException("New Error");
}

void p()
{
try
{
m();
}
catch (Exception e)
{
System.out.println(e);

Sou.Venutai Chavan Polytechnic,Pune. 12


Java Programming (22412)

}
}

public static void main(String args[])


{
simple obj = new simple();
obj.p();
System.out.println("Normal flow");
}
}

Output –

C:\my>java simple
java.io.IOException: New Error
Normal flow

throw throws
It is used to explicitly throw an exception It is used to declare an exception
Checked exceptions cannot be propagated Checked exceptions can be propagated without
without throw throw
It is followed by an instance It is followed by a class

It is used within method It is used with method signature


Cannot throw multiple exceptions Can declare multiple exceptions
For e.g.
void show() throws IOException,
SQLException,….

User Define Exception


- Can create user define or custom exceptions by defining a subclass of Exception
(subclass of Throwable)

Syntax –
Class class_name extends Exception
{
//Methods & implementation
}
Program –
class MyException extends Exception
{
public String show()
{

Sou.Venutai Chavan Polytechnic,Pune. 13


Java Programming (22412)

return "My Error";


}
}

class TestMy
{
public static void main(String args[])
{
int a=10;
try
{
if(a==10)
{
throw new MyException();
}
else
{
System.out.println("other code");
}
}
catch(MyException e)
{
System.out.println("Exception =" + e.show());
}
}
}

Output –

C:\my>java TestMy
Exception =My Error

Multithreading
 Multithreading in java is a process of executing multiple threads simultaneously.
 Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
 But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation etc.

Sou.Venutai Chavan Polytechnic,Pune. 14


Java Programming (22412)

Advantages of Java Multithreading

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

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

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Life Cycle of Thread

Newborn State –

 When the thread is created, it will be in Newborn State.


 The thread is just created still its not running.

Sou.Venutai Chavan Polytechnic,Pune. 15


Java Programming (22412)

 Thread can move to running mode by invoking the start() method and it can be killed by
using stop() method.

Runnable State –

 In this state Thread is ready for execution & it is waiting for the availability of the
processor.
 By yield() method, it is possible to move control to another thread.

Running State –

 It means thread is in its execution mode because the control of CPU is given to that
particular thread (i.e. Processor has given its time to that thread).
 It can be move in three different situation from running mode.
o Suspended() – a suspended thread can be revived by using resume() method.
o Sleep(t) – a thread can be sleep for specific time period using sleep() method,
where time is in milliseconds. The thread re-enters into runnable state as soon as
this time period is elapsed.
o Wait() – a thread is waiting until some event occurs. A thread can be scheduled to
run again using the notify() method.

Blocked State –

 A thread is called in Blocked State when it is not allowed to entering in Runnable State or
Running State.
 It happens when thread is in waiting mode, suspended or in sleeping mode.
 A blocked thread is considered as “not runnable” but not dead.

Dead Thread –

 When a thread is completed executing its run() method the life cycle of that particular
thread is end.

Sou.Venutai Chavan Polytechnic,Pune. 16


Java Programming (22412)

 We can kill thread by invoking stop() method for that particular thread and send it to be
in Dead State.

Thread Creation

There are two ways to create a thread:

 By extending Thread class


 By implementing Runnable interface.

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

Commonly used Constructors of Thread class:

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

Implementing the Runnable Interface

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, which is
of form,

public void run()

 run() method introduces a concurrent thread into your program. This thread will end
when run() method terminates.
 You must specify the code that your thread will execute inside run() method.
 run() method can call other methods, can use other classes and declare variables just like
any other normal method.

Sou.Venutai Chavan Polytechnic,Pune. 17


Java Programming (22412)

class MyThread implements Runnable


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

class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}

Output –

concurrent thread started running..

To call the run() method, start() method is used. On calling start(), a new stack is provided to
the thread and run() method is called to introduce the new thread into the program.

Extending Thread class

This is another way to create a thread by a new class that extends Thread class and create an
instance of that class. The extending class must override run() method which is the entry point of
new thread.

class MyThread extends Thread


{

Sou.Venutai Chavan Polytechnic,Pune. 18


Java Programming (22412)

public void run()


{
System.out.println("Concurrent thread started running..");
}
}

classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}

Output :

concurrent thread started running..

Here, we must override the run() and then use the start() method to run the thread. Also, when
you create MyThread class object, Thread class constructor will also be invoked, as it is the
super class, hence MyThread class object acts as Thread class object.

Thread Methods

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.

Sou.Venutai Chavan Polytechnic,Pune. 19


Java Programming (22412)

7. public int setPriority(int priority): changes the priority of the thread.


8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Thread Priority

 Each java thread has its own priority which decides the order of thread to be schedule.
 The threads of equal priority will be given same treatment by java scheduler and they will
follow the FCFS (First Come First Serve) algorithm.
 User can also set the priority of thread by using the setPriority() method as follow:

ThreadName.setPriority(int Number);

The Thread class defines few priority constants:

MIN_PRIORITY = 1

NORM_PRIORITY = 5

Sou.Venutai Chavan Polytechnic,Pune. 20


Java Programming (22412)

MAX_PRIORITY = 10

 The getPriority() method returns the priority of the thread.


 In any Thread the default priority is NORM_PRIORITY
 Whenever more than one threads are ready to run java system select the highest priority
thread and execute it
 If another thread of higher priority comes the running thread will be pre-empted by the
incoming thread and current thread will move to runnable state.

Program –

class FT extends Thread

public void run()

System.out.println("First Thread");

for(int i = 1; i<=5; i++)

System.out.println("\t First i = " +i);

class ST extends Thread

Sou.Venutai Chavan Polytechnic,Pune. 21


Java Programming (22412)

public void run()

System.out.println("Second Thread");

for(int j = 1; j<=5; j++)

System.out.println("\t Second j = " +j);

public class Thread_Priority

public static void main(String[] args)

FT t1 = new FT();

ST t2 = new ST();

t1.setPriority(Thread.MIN_PRIORITY);

t2.setPriority(Thread.MAX_PRIORITY);

System.out.println("First Thread Priority ="+t1.getPriority());

t1.start();

Sou.Venutai Chavan Polytechnic,Pune. 22


Java Programming (22412)

System.out.println("Second Thread Priority ="+t2.getPriority());

t2.start();

Output –

First Thread Priority =1

Second Thread Priority =10

Second Thread

Second j = 1

Second j = 2

Second j = 3

Second j = 4

Second j = 5

First Thread

First i = 1

First i = 2

First i = 3

First i = 4

First i = 5

Sou.Venutai Chavan Polytechnic,Pune. 23


Java Programming (22412)

Synchronization

What is a Monitor?

A monitor is a set of multiple routines which are protected by a mutual exclusion lock. None of
the routines in the monitor can be executed by a thread until that thread acquires the lock. This
means that only ONE thread can execute within the monitor at a time. Any other threads must
wait for the thread that’s currently executing to give up control of the lock.

However, a thread can actually suspend itself inside a monitor and then wait for an event to
occur. If this happens, then another thread is given the opportunity to enter the monitor. The
thread that was suspended will eventually be notified that the event it was waiting for has now
occurred, which means it can wake up and reacquire the lock.

What is a Semaphore?

A semaphore is a simpler construct than a monitor because it’s just a lock that protects a
shared resource – and not a set of routines like a monitor. The application must acquire the lock
before using that shared resource protected by a semaphore.

Example of a Semaphore – a Mutex

A mutex is the most basic type of semaphore, and mutex is short for mutual exclusion.

In a mutex, only one thread can use the shared resource at a time. If another thread wants to
use the shared resource, it must wait for the owning thread to release the lock.

Lock –

 Synchronization is built around an internal entity known as Lock.


 Every object has a lock associated with Lock.
 A thread that needs consistent access to an object’s fields has to acquire the object’s Lock
before accessing them & release the lock when it is done.

Types of Syncronization –

 Process Synchronization

 Thread Synchronization

Sou.Venutai Chavan Polytechnic,Pune. 24


Java Programming (22412)

Thread Synchronization

 Mutual Exclusion –

 Synchronized block

 Synchronized method

 Inter-Thread Communication

Program -

Without Syncronization –

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

class FT implements Runnable


{
table t;
FT(table t)
{ this.t=t; }
public void run()
{
t.print(5);
}
}

Sou.Venutai Chavan Polytechnic,Pune. 25


Java Programming (22412)

class ST implements Runnable


{
table t;
ST(table t)
{ this.t=t; }
public void run()
{
t.print(100);
}
}

class use
{
public static void main(String args[])
{
table obj = new table();
FT f = new FT(obj);
ST s = new ST(obj);

Thread t1=new Thread(f);


Thread t2=new Thread(s);

t1.start();
t2.start();
}
}

Output -

C:\my>java use
5
100
10
200
15
300
20
400
25
500

Program –

class table
{

Sou.Venutai Chavan Polytechnic,Pune. 26


Java Programming (22412)

synchronized void print(int n)


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

class FT extends Thread


{
table t;
FT(table t)
{ this.t=t; }
public void run()
{
t.print(5);
}
}

class ST extends Thread


{
table t;
ST(table t)
{ this.t=t; }
public void run()
{
t.print(100);
}
}

class use
{
public static void main(String args[])
{
table obj = new table();
FT t1 = new FT(obj);
ST t2 = new ST(obj);

Sou.Venutai Chavan Polytechnic,Pune. 27


Java Programming (22412)

t1.start();
t2.start();
}
}

Output –
C:\my>java use
5
10
15
20
25
100
200
300
400
500

Inter Thread Communication –

class message
{
synchronized void dispHi()
{
System.out.println("Hi");
}

synchronized void dispHello()


{
System.out.println("Hello");
}

class FT implements Runnable{


message m;
FT(message m1)
{
m=m1;
}
public void run()
{
while(true)
m.dispHi();

Sou.Venutai Chavan Polytechnic,Pune. 28


Java Programming (22412)

}
}

class ST implements Runnable


{
message m;
ST(message m1)
{
m=m1;
}
public void run()
{
while(true)
m.dispHello();
}
}

class TComm
{
public static void main(String args[])
{
message obj = new message();

FT t1=new FT(obj);
ST t2=new ST(obj);

Thread t=new Thread(t1);


Thread tt=new Thread(t2);

t.start();
tt.start();
}
}

Output –

Hi

Hi

Hello

Hi

Hello

Sou.Venutai Chavan Polytechnic,Pune. 29


Java Programming (22412)

Hello …

Using wait() & notify()

class message
{
boolean r=false;

synchronized void dispHi()


{
if(!r)
try
{
wait();
}
catch(Exception e)
{
System.out.println("Error");
}
System.out.println("Hi");
r= false;
notify();
}

synchronized void dispHello()


{
if(r)
try
{
wait();
}
catch(Exception e)
{
System.out.println("Error");
}
System.out.println("Hello");
r= true;
notify();
}

class FT implements Runnable{


message m;
FT(message m1)

Sou.Venutai Chavan Polytechnic,Pune. 30


Java Programming (22412)

{
m=m1;
}
public void run()
{
while(true)
m.dispHi();
}
}

class ST implements Runnable


{
message m;
ST(message m1)
{
m=m1;
}
public void run()
{
while(true)
m.dispHello();
}
}

class TComm
{
public static void main(String args[])
{
message obj = new message();

FT t1=new FT(obj);
ST t2=new ST(obj);

Thread t=new Thread(t1);


Thread tt=new Thread(t2);

t.start();
tt.start();
}
}

Output –

Hi

Hello

Sou.Venutai Chavan Polytechnic,Pune. 31


Java Programming (22412)

Hi

Hello

Hi

Hello

Inter Thread Communication

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


communicate with each other.

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


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

 wait() - 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.
 notify() - Wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
 notifyAll() - Wakes up all threads that are waiting on this object's monitor.

class Customer

int balance=10000;

synchronized void withdraw(int amount)

System.out.println("going to withdraw...");

if(balance<amount)

System.out.println("Less balance; waiting for deposit...");

Sou.Venutai Chavan Polytechnic,Pune. 32


Java Programming (22412)

try{

wait();

}catch(Exception e){}

balance-=amount;

System.out.println("withdraw completed...");

synchronized void deposit(int amount)

System.out.println("going to deposit...");

balance+=amount;

System.out.println("deposit completed... ");

notify();

class ft extends Thread

Customer o;

ft(Customer obj)

{ o=obj; }

public void run(){o.withdraw(15000);}

Sou.Venutai Chavan Polytechnic,Pune. 33


Java Programming (22412)

class st extends Thread

Customer o;

st(Customer obj)

{ o=obj; }

public void run(){o.deposit(10000);}

class Test{

public static void main(String args[])

final Customer c=new Customer();

ft t1 = new ft(c);

st t2 = new st(c);

t1.start();

t2.start();

Output: going to withdraw...


Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Sou.Venutai Chavan Polytechnic,Pune. 34


Java Programming (22412)

Thread Programs
Main Thread Program – currentThread(), setName(), setPriority()
class MainThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current Thread =" +t);
t.setName("MAINTHREAD");
System.out.println("Current Thread =" +t);
t.setPriority(3);
System.out.println("Current Thread =" +t);
}
}

Output –
Current Thread =Thread[main,5,main]
Current Thread =Thread[MAINTHREAD,5,main]
Current Thread =Thread[MAINTHREAD,3,main]

Sou.Venutai Chavan Polytechnic,Pune. 35


Java Programming (22412)

Creating thread by Extending Thread Class


class FT extends Thread
{
public void run()
{
System.out.println("Hello");
}
}

public class ThreadDemo


{
public static void main(String args[])
{
FT t1=new FT();
t1.setName("First");
t1.start();
}
}
Output – Hello

Creating multiple threads by extending Thread Class (Multiple threads performing same
task)
class FT extends Thread
{
public void run()
{

Sou.Venutai Chavan Polytechnic,Pune. 36


Java Programming (22412)

System.out.println("Hello");
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FT t1=new FT();
t1.setName("First");
t1.start();

FT t2=new FT();
t2.setName("Second");
t2.start();

FT t3=new FT();
t3.setName("Third");
t3.start();
Hello
}
}
Output –
Hello
t2 t3
t1
Hello
Hello

Creation of Thread using Constructor to setName() & start()


class FT extends Thread

Sou.Venutai Chavan Polytechnic,Pune. 37


Java Programming (22412)

{
FT()
{
setName("FirstThread");
start();
}
public void run()
{
System.out.println("Hello");
System.out.println(getName());
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FT t1=new FT();
}
}

Output –
Hello
FirstThread

Creation of 2 threads performing different tasks using constructor


class FT extends Thread
{
FT()
{

Sou.Venutai Chavan Polytechnic,Pune. 38


Java Programming (22412)

setName("FirstThread");
start();
}
public void run()
{
System.out.println("Hello");
System.out.println(getName());
}
}

class ST extends Thread


{
ST()
{
setName("SecondThread");
start();
}

public void run()


{
System.out.println("Bye");
System.out.println(getName());
}
}

public class ThreadDemo


{

Sou.Venutai Chavan Polytechnic,Pune. 39


Java Programming (22412)

public static void main(String args[])


{
FT t1=new FT();
ST t2=new ST();
}
}

Output –
Hello
FirstThread
Bye
SecondThread

Creation of Thread, One thread should print Even numbers & another thread should print
Odd numbers.
class FT extends Thread
{

public void run()


{
for(int i=0;i<10;i++)
{
if(i % 2==0)
{
System.out.println(i);
}
}
}
}

Sou.Venutai Chavan Polytechnic,Pune. 40


Java Programming (22412)

class ST extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
if(i % 2 !=0)
{
System.out.println(i);
}
}
}
}

public class ThreadDemo


{
public static void main(String args[])
{
FT t1=new FT();
t1.setName("Even");
System.out.println(t1.getName());
t1.start();

ST t2=new ST();
t2.setName("Odd");
System.out.println(t2.getName());
t2.start();

Sou.Venutai Chavan Polytechnic,Pune. 41


Java Programming (22412)

Output –
Even
Odd
0
2
4
6
8
1
3
5
7
9

Creating thread by Implementing Runnable Class


class FT implements Runnable
{
public void run()
{
System.out.println("Thread");
for(int i=1;i<=5;i++)
{
System.out.println(i);
}

Sou.Venutai Chavan Polytechnic,Pune. 42


Java Programming (22412)

System.out.println("Exit...");
}
}

public class Thread_Interface


{
public static void main(String[] args)
{
FT obj = new FT(); //class object
Thread t1 = new Thread(obj);
t1.start();
}
}

Output –

Thread
1
2
3
4
5
Exit...

Create 2 Threads, one should print “Hello” and second should print “Bye” with
implementing Runnable Interface
class FT implements Runnable
{
public void run()

Sou.Venutai Chavan Polytechnic,Pune. 43


Java Programming (22412)

{
System.out.println("First Thread");
System.out.println("Hello");
System.out.println("Exit...");
}
}
class ST implements Runnable
{
public void run()
{
System.out.println("Second Thread");
System.out.println("Bye");
System.out.println("Exit...");
}
}
public class Thread_Interface
{
public static void main(String[] args)
{
FT objF = new FT(); //class object
Thread t1 = new Thread(objF);
t1.start();

ST objS = new ST(); //class object


Thread t2 = new Thread(objS);
t2.start();
}

Sou.Venutai Chavan Polytechnic,Pune. 44


Java Programming (22412)

Output –
First Thread
Hello
Exit...
Second Thread
Bye
Exit...

Sou.Venutai Chavan Polytechnic,Pune. 45

You might also like