0% found this document useful (0 votes)
2 views20 pages

Java Unit III Part II

The document provides an overview of Java programming concepts related to exception handling and multithreading. It explains the fundamentals of exception handling, types of exceptions, and the Java thread model, including the differences between threads and processes, as well as multitasking. Additionally, it describes how to create threads using both the Thread class and the Runnable interface, along with the lifecycle of a thread and its priority management.
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)
2 views20 pages

Java Unit III Part II

The document provides an overview of Java programming concepts related to exception handling and multithreading. It explains the fundamentals of exception handling, types of exceptions, and the Java thread model, including the differences between threads and processes, as well as multitasking. Additionally, it describes how to create threads using both the Thread class and the Runnable interface, along with the lifecycle of a thread and its priority management.
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

JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND

SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

II [Link] II- Semester


CS405PC
Java Programming (R18) 2021-22

UNIT-III PART-II

Prepared by [Link], Associate Professor, CSE Dept Page 1


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

UNIT-III

Exception handling - Fundamentals of exception handling, Exception types, Termination or


resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested
try statements, throw, throws and finally, built- in exceptions, creating own exception sub
classes.
Multithreading- Differences between thread-based multitasking and process-based
multitasking, Java thread model, creating threads, thread priorities, synchronizing threads,
inter thread communication.

Multithreading in java
Threads: Introduction:
● One of the exciting features of the Windows operating system is that-it allows the
user to handle multiple tasks together. This facility in the Windows operating system
is called multitasking.
● In java, we can write the programs that perform multitasking using the
multithreading concept. Thus java allows multiple control flows in a single program
by means of multithreading.

Definition: Thread is a tiny program running continuously. It is sometimes called as


light-weight-process. But there lies differences between thread and process.

Difference between thread and process:


Thread Process
[Link] is a light weight process [Link] is heavy weight process
2. Threads do not require separate address 2. Each process requires separate address
space for its execution. It runs in the address space to execute.
space of the process to which it belongs to

Difference between Multithreading and Multitasking:


Multithreading Multitasking
[Link] is a fundamental unit of [Link] or process is a fundamental unit
multithreading of multitasking environment
2. Multiple parts of a single program get [Link] programs get executed in
executed in multithreading environment. multitasking environment

Prepared by [Link], Associate Professor, CSE Dept Page 2


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
3. During multithreading the processor 3. During multitasking the processor
switches between multiple threads of the switches between multiple programs or
program. processes.
[Link] is cost effective because CPU can be [Link] is expensive because when a particular
shared among multiple threads at a time. process uses CPU other processes has to
wait.
[Link] is highly efficient. [Link] is less efficient in comparison with
multithreading.
[Link] helps in developing efficient application 6. It helps in developing efficient operating
programs. system programs.

In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking. There are two types of multitasking, and they are as follows.

✔ Process-based multitasking

✔ Thread-based multitasking

Difference between process-based and thread-based multitasking

Process-based multitasking Thread-based multitasking

It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires separate address space for Threads share same address space.
each.

Process never gains access over idle time of Thread gain access over idle time of CPU.
CPU.

Inter process communication is expensive. Inter thread communication is not


expensive.

Java Thread Model

Prepared by [Link], Associate Professor, CSE Dept Page 3


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time. This type of program is known as a
multithreading program. Each part of this program is called a thread. Every thread defines a
separate path of execution in java.

Thread always exists in any one of the following states.


● New or create state
● Runnable state
● Waiting state
● Timed waiting state
● Blocked state
● Terminated state

Thread Life Cycle

In java, a thread goes through different states throughout its execution. These stages are
called thread life cycle states or phases. A thread may in any of the states like new, ready or
runnable, running, blocked or wait, and dead or terminated state. The life cycle of a thread
in java is shown in the following figure.

New state
When thread starts its life cycle it enters in the new state or a create state.
When a thread object is created using new, then the thread is said to be in the New state.
This state is also known as Born state.
Example
Prepared by [Link], Associate Professor, CSE Dept Page 4
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Thread t1 = new Thread();

Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.
Example
[Link]( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method
of a thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
Sometimes one thread has to undergo in waiting state because another thread starts
executing.

There is a provision to keep a particular thread waiting for some time interval. This allows
to execute high prioritized threads first. After the timing gets over, the thread in waiting
state enters in Runnable state.

When a thread is in the blocked or waiting state, it may move to Runnable state due to
reasons like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method
called, resume( ) method called, etc.

When a particular thread issues an input/output request then operating system sends it in
blocked state until the I/O operation gets completed. After the I/O completion the thread is
sent back to the Runnable state.

Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.

Creating threads in java


In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.

The java programming language provides two methods to create threads, and they are listed
below.

Prepared by [Link], Associate Professor, CSE Dept Page 5


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
✔ Using Thread class (by extending Thread class)

✔ Using Runnable interface (by implementing Runnable interface)


Let's see how to create threads using each of the above.

Extending Thread class;


The java contains a built-in class Thread inside the [Link] package. The Thread class
contains all the methods that are related to the threads.

To create a thread using Thread class, follow the step given below.

Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.

Example:
class SampleThread extends Thread{

public void run() {


[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++) {
[Link]("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}
Output:
Thread about to start...
Thread is under Running...
i=1
i=2
Prepared by [Link], Associate Professor, CSE Dept Page 6
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10

Implementing Runnable interface


The java contains a built-in interface Runnable inside the [Link] package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to
the threads.

To create a thread using Runnable interface, follow the step given below.

Step-1: Create a class that implements Runnable interface.


Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.
Example:
class SampleThread implements Runnable{
public void run() {
[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++) {
[Link]("i = " + i);
}
}
}

public class My_Thread_Test1 {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
[Link]("Thread about to start...");
[Link]();
}
}
Prepared by [Link], Associate Professor, CSE Dept Page 7
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Output:
Thread about to start...
Thread is under Running...
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
Note:
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create the Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.

More about Thread class


The Thread class in java is a subclass of Object class and it implements Runnable interface.
The Thread class is available inside the [Link] package.

The Thread class has the following syntax.

class Thread extends Object implements Runnable{


...
}

The Thread class has the following constructors.

● Thread( )
● Thread( String threadName )
● Thread( Runnable objectName )
● Thread( Runnable objectName, String threadName )

The Thread classes contain the following methods.


Method Description Return
Value

run( ) Defines actual task of the thread. void

Prepared by [Link], Associate Professor, CSE Dept Page 8


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description Return
Value

start( ) It moves the thread from Ready state to Running state by void
calling run( ) method.

setName(String Assigns a name to the thread. void


)

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

currentThread( Returns the reference of the thread that currently in running void
) state.

sleep( long ) Moves the thread to blocked state till the specified number of void
milliseconds.

isAlive( ) Tests if the thread is alive. boolean

yield( ) Tells to the scheduler that the current thread is willing to yield void
its current use of a processor.

join( ) Waits for the thread to end. void

The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and
resume( ).
Example:
// Using the Thread Class: Thread(String Name). We can directly use the Thread class to initiate new
threads using the constructors.

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class

Prepared by [Link], Associate Professor, CSE Dept Page 9


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Thread t= new Thread();

// the start() method moves the thread to the active state


[Link]();
[Link]("CSE Thread");
[Link]([Link]());

// getting the thread name by invoking the getName() method

String str = [Link]();


[Link](str);
}
}
Output:
5
CSE Thread

Java Thread Priority


In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java,
the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and
priority 10 is considered as the highest priority. The thread with more priority allocates the
processor first.

The java programming language Thread class provides two methods setPriority(int), and
getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and
they are listed below.

✔ MAX_PRIORITY - It has the value 10 and indicates highest priority.

✔ NORM_PRIORITY - It has the value 5 and indicates normal priority.

✔ MIN_PRIORITY - It has the value 1 and indicates lowest priority.


Note:
The default priority of any thread is 5 (i.e. NORM_PRIORITY).

setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an
integer range from 1 to 10 as an argument and returns nothing (void).

Prepared by [Link], Associate Professor, CSE Dept Page 10


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The regular use of the setPriority( ) method is as follows.

Example
[Link](4);
or
[Link](MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
take any argument and returns name of the thread as String.

The regular use of the getPriority( ) method is as follows.

Example
String threadName = [Link]();

Example Program
class SampleThread extends Thread{
public void run() {
[Link]("Inside SampleThread");
[Link]("Current Thread: " + [Link]().getName());
}
}

public class My_Thread_TestPriority {

public static void main(String[] args) {


SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
SampleThread threadObject3 = new SampleThread();
SampleThread threadObject4 = new SampleThread();
SampleThread threadObject5 = new SampleThread();
SampleThread threadObject6 = new SampleThread();

[Link]("first");
[Link]("second");
[Link]("third");
[Link]("four");
[Link]("five");
[Link]("six");

[Link](7);
[Link](5);

Prepared by [Link], Associate Professor, CSE Dept Page 11


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](4);
[Link](3);
[Link](7);
[Link](9);

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Inside SampleThread
Inside SampleThread
Inside SampleThread
Current Thread: first
Inside SampleThread
Inside SampleThread
Current Thread: five
Current Thread: four
Inside SampleThread
Current Thread: third
Current Thread: six
Current Thread: second

Note:
In java, it is not guaranteed that threads execute according to their priority because it
depends on JVM specification that which scheduling it chooses.

If there are two threads that have the same priority, then one cannot predict which thread
will get the chance to execute first. The execution then is dependent on the thread
scheduler's algorithm (First Come First Serve, Round-Robin, etc.)

Java Thread Synchronization


The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.
Note:

Prepared by [Link], Associate Professor, CSE Dept Page 12


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The synchronization is the process of allowing only one thread to access a shared resource
at a time.
In java, the synchronization is achieved using the following concepts.

✔ Mutual Exclusion

✔ Inter thread communication

Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another
while they accessing the shared resource. In java, mutual exclusion is achieved using the
following concepts.

● Synchronized method
● Synchronized block

Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it
at a time. When an object calls a synchronized method, it put a lock on that method so that
other objects or thread that is trying to call the same method must wait, until the lock is
released. Once the lock is released on the shared resource, one of the threads among the
waiting threads will be allocated to the shared resource.

Prepared by [Link], Associate Professor, CSE Dept Page 13


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22

In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized
method). When thread-1 completes it task, then one of the threads that are waiting is
allocated with the synchronized method, in the above it is thread-3.
Example:

class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
[Link](n + " * " + i + " = " + i*n);
}
}

class MyThread_1 extends Thread{


Table table = new Table();
int number;
MyThread_1(Table table, int number){
[Link] = table;
[Link] = number;
}

Prepared by [Link], Associate Professor, CSE Dept Page 14


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public void run() {
[Link](number);
}
}

class MyThread_2 extends Thread{

Table table = new Table();


int number;
MyThread_2(Table table, int number){
[Link] = table;
[Link] = number;
}
public void run() {
[Link](number);
}
}
public class ThreadSynchronizationExample {

public static void main(String[] args) {


Table table = new Table();
MyThread_1 thread_1 = new MyThread_1(table, 5);
MyThread_2 thread_2 = new MyThread_2(table, 10);
thread_1.start();
thread_2.start();
}
}
Output:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
Prepared by [Link], Associate Professor, CSE Dept Page 15
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of
lines in a method. For example, let's consider a method with 20 lines of code where we want
to synchronize only a sequence of 5 lines code, we use the synchronized block.

The following syntax is used to define a synchronized block.

Syntax
synchronized(object){
...
block code
...
}

Example:
import [Link].*;
class NameList {
String name = "";
public int count = 0;

public void addName(String name, List<String> namesList){


synchronized(this){
[Link] = name;
count++;
}
[Link](name);
}

public int getCount(){


return count;
}
}
public class SynchronizedBlockExample {
public static void main (String[] args)

Prepared by [Link], Associate Professor, CSE Dept Page 16


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
{
NameList namesList_1 = new NameList();
NameList namesList_2 = new NameList();
List<String> list = new ArrayList<String>();
namesList_1.addName("VarunJoel", list);
namesList_2.addName("Snigdha", list);
[Link]("Thread1: " + namesList_1.name + ", " + namesList_1.getCount() +
"\n");
[Link]("Thread2: " + namesList_2.name + ", " + namesList_2.getCount() +
"\n");
}
}
Output:
Thread1: VarunJoel, 1
Thread2: Snigdha, 1

Note:
The complete code of a method may be written inside the synchronized block, where it
works similarly to the synchronized method.

Java Inter Thread Communication


Inter thread communication is the concept where two or more threads communicate to solve
the problem of polling. In java, polling is the situation to check some condition repeatedly,
to take appropriate action, once the condition is true. That means, in inter-thread
communication, a thread waits until a condition becomes true such that other threads can
execute its task. The inter-thread communication allows the synchronized threads to
communicate with each other.

Java provides the following methods to achieve inter thread communication.


● wait( )
● notify( )
● notifyAll( )
The following table gives detailed description about the above methods.
Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

Prepared by [Link], Associate Professor, CSE Dept Page 17


JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description

void It wakes up all the threads that called wait( ) on the same object.
notifyAll()

Note:
Calling notify( ) or notifyAll( ) does not actually give up a lock on a resource.

Let's look at an example problem of producer and consumer. The producer produces the
item and the consumer consumes the same. But here, the consumer cannot consume until the
producer produces the item and producer cannot produce until the consumer consumes the
item that already been produced. So here, the consumer has to wait until the producer
produces the item, and the producer also needs to wait until the consumer consumes the
same. Here we use the inter-thread communication to implement the producer and consumer
problem.

Example:
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()


{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link]("Consummed:" + item);
valueSet = false;
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
return item;
}

synchronized void putItem(int item) {


Prepared by [Link], Associate Professor, CSE Dept Page 18
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
while (valueSet)
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link] = item;
valueSet = true;
[Link]("Produced: " + item);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
[Link] = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
class Consumer implements Runnable{

ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
[Link] = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
[Link]();
Prepared by [Link], Associate Professor, CSE Dept Page 19
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
}
}
}

class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);

}
}

Output:
Produced: 0
Consummed:0
Produced: 1
Consummed:1
Produced: 2
Consummed:2
Produced: 3
Consummed:3
Produced: 4
Consummed:4
Produced: 5
Consummed:5
Produced: 6
Consummed:6
Produced: 7
Consummed:7
Produced: 8
Consummed:8
Produced: 9
Consummed:9
Produced: 10
Consummed:10………

Note:
All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized methods
only.

Prepared by [Link], Associate Professor, CSE Dept Page 20

You might also like