0% found this document useful (0 votes)
10 views31 pages

bATCH 03 PPT (M2)

Uploaded by

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

bATCH 03 PPT (M2)

Uploaded by

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

O

o
o ps
b je c t
orie
nt ed s y s t em s
programming
BRANCH : CSE 231FA04053 - SONU KUMAR
SUBJECT : OOPS
231FA04062 - ALLA VARSHITHA SAI REDDY
SECTION : I
MODULE : 02 231FA04077 - SAI SREEJA GUJJIDI
BATCH : 03
231FA4639 - BANDLAMUDI BHUVAN

SUBMITTED TO:
DR. O.BHASKAR
CONTENTS
01 PROBLEM STATEMENT 04 SOURCE CODE

02 DESCRIPTION 05 TEST CASES

03 ALGORITHM 06 CONCLUSOION
PROBLEM STATEMENT:
a) Describe a situation in a Java application where four threads might encounter a deadlock while attempting to
access shared resources, requiring locks on two different objects. Identify the conditions leading to deadlock,
such as both threads holding a lock on one resource while waiting for the other, and being unable to release
their locks. Write a Java program that illustrates this deadlock scenario, where Thread A locks Resource 1 and
attempts to lock Resource 2, while Thread B locks Resource 2 and attempts to lock Resource 1. Then, refactor
the program to avoid deadlock by establishing a consistent order for locking resources and implementing
timeout mechanisms for acquiring locks. Finally, run the modified code to demonstrate that the deadlock has
been resolved.
DESCRIBTION:
Part-A:
(a):
• Mutual Exclusion: Threads hold locks on resources, preventing others from accessing.
• Hold and Wait: Threads hold one lock while waiting for another.
• No Preemption: Operating system doesn't intervene to prevent deadlock.
• Circular Wait: Threads form a circular chain, each waiting for another thread's resource.
(b):
• PriorityThread Class: This class extends the Thread class and implements the logic for running a loop with 1000
iterations. Each iteration prints the current iteration number.
• Main Method: In the main method, three instances of PriorityThread are created, each assigned a different
priority: MAX_PRIORITY, NORM_PRIORITY and MIN_PRIORITY.
• Thread Execution: All three threads are started simultaneously using the start() method. The Thread.sleep(1)
statement simulates some work done by each thread.
• Thread Execution: All three threads are started simultaneously using the start() method. The
Thread.sleep(1) statement simulates some work done by each thread.
• Thread Priorities: The program illustrates how thread priorities influence the scheduling of threads by
the JVM. Threads with higher priorities are executed more frequently than those with lower priorities.
ALGORITHM:
1. Define Resource1 and Resource2 Classes:
• Create two classes, Resource1 and Resource2, each with a synchronized method:
• useResource1() in Resource1: Pauses execution for 1 second.
• useResource2() in Resource2: Pauses execution for 1 second.
2. Define Threads A, B, C, and D:
• Each thread class (ThreadA, ThreadB, ThreadC, ThreadD) extends Thread.
• Each class has two instance variables (r1 and r2) representing Resource1 and Resource2.
3. Constructor:
• The constructor takes Resource1 and Resource2 objects as parameters and assigns them to r1 and r2.
4. run() Method:
• Each thread’s run() method follows these steps:
• Acquire a lock on r1 (using synchronized(r1)).
• Print a message indicating the thread has locked r1.
• Pause execution for 1 second.
• Acquire a lock on r2 (using synchronized(r2)).
• Print a message indicating the thread has locked r2.
• Call useResource2() on r2.
• Release the lock on r2 and r1.
• After releasing both locks, call useResource1() on r1 to simulate usage outside of locks.
5. Define the DeadlockExample Class:
• In main(), create two resource instances, r1 and r2.
• Instantiate four threads (ThreadA, ThreadB, ThreadC, ThreadD) with r1 and r2 as arguments.
6. Start Threads:
• Start all four threads, allowing each to execute its run() method.
7. Execution Flow and Potential Deadlock:
• Each thread attempts to acquire r1 first and then r2. If two threads lock r1 and are waiting for r2, it may lead to a
deadlock if both threads block each other by holding different resources that the other needs.
8. End of Execution:
• If a deadlock occurs, some threads will not complete, resulting in the program hanging indefinitely.
• If no deadlock occurs, the program prints the execution flow and exits successfully.
SOURCE CODE:
class Resource1 {
public synchronized void useResource1() {
System.out.println("Thread: using Resource 1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Resource2 {
public synchronized void useResource2() {
System.out.println("Thread: using Resource 2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadA extends Thread {
private Resource1 r1;
private Resource2 r2;
public ThreadA(Resource1 r1, Resource2 r2) {
this.r1 = r1;
this.r2 = r2;
}
public void run() {
synchronized (r1) {
System.out.println("Thread A: locked resource 1");
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (r2) {
System.out.println("Thread A: locked resource 2");
r2.useResource2();
}
}
r1.useResource1();
}
}
class ThreadB extends Thread {
private Resource1 r1;
private Resource2 r2;
public ThreadB(Resource1 r1, Resource2 r2) {
this.r1 = r1;
this.r2 = r2;
}
public void run() {
synchronized (r1) {
System.out.println("Thread B: locked resource 1");
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (r2) {
System.out.println("Thread B: locked resource 2");
r2.useResource2();
}
}
class ThreadC extends Thread {
private Resource1 r1;
private Resource2 r2;
public ThreadC(Resource1 r1, Resource2 r2) {
this.r1 = r1;
this.r2 = r2;
}
public void run() {
synchronized (r1) {
System.out.println("Thread C: locked resource 1");
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (r2) {
System.out.println("Thread C: locked resource 2");
r2.useResource2();
}}
r1.useResource1();
}}
class ThreadD extends Thread {
private Resource1 r1;
private Resource2 r2;
public ThreadD(Resource1 r1, Resource2 r2) {
this.r1 = r1;
this.r2 = r2;
}
public void run() {
synchronized (r1) {
System.out.println("Thread D: locked resource 1");
try {
Thread.sleep(1000); }
catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (r2) {
System.out.println("Thread D: locked resource 2");
r2.useResource2();
}
}
r1.useResource1();
}}public class DeadlockExample {
public static void main(String[] args) {
Resource1 r1 = new Resource1();
Resource2 r2 = new Resource2();
ThreadA t1 = new ThreadA(r1, r2);
ThreadB t2 = new ThreadB(r1, r2);
ThreadC t3 = new ThreadC(r1, r2);
ThreadD t4 = new TAhreadD(r1, r2);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
OUTPUT:
PROBLEM STATEMENT:

Develop a Java program that demonstrates the effect of thread priorities on thread scheduling. Create
three threads with different priorities: MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY. Each thread
should execute a loop that runs 2000 iterations and print the current iteration number.
• Requirements:
1.Write a class PriorityThread that extends Thread and implements the logic for running a loop with 2000
iterations. Each iteration should print the current iteration number.
2. In the main method, create three instances of PriorityThread, each assigned a different priority
(MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY).
3.Start all three threads simultaneously and use Thread.sleep() to simulate some work done by each
thread.
4.After all threads complete, print out how many times each thread executed to observe the effect of
priority on thread execution. The program should illustrate how thread priorities influence the scheduling
of threads by the JVM.
ALGORITHM:
1.Define PriorityThread Class:
•Extend the Thread class.
•Define a private integer iterationsCount initialized to 0 to track the number of iterations executed by the thread.
2.Implement run() Method:
•Override the run() method to execute a loop 2000 times.
•For each iteration:
•Pause execution with Thread.sleep(1) to simulate some workload.
•Increment iterationsCount.
•Print the current thread name and iteration count.
•Catch any InterruptedException that occurs during sleep and print the stack trace.
3.Define getIterationsCount() Method:
•Create a getter getIterationsCount() to return the iterationsCount after thread execution.
4.Main Class (ThreadPriorityDemo):
• Create three PriorityThread objects:
•Set names as "High Priority Thread," "Normal Priority Thread," and "Low Priority Thread.“
•Assign different priorities using setPriority(): MAX_PRIORITY, NORM_PRIORITY, and MIN_PRIORITY for high, normal, and low
priority threads, respectively.
5.Start Threads:
•Start each of the three threads, invoking their run() methods concurrently.
6.Wait for Completion:
•Use join() on each thread to wait until all threads complete before moving to the next step.
•Catch any InterruptedException that may arise.
7.Display Iteration Counts:
•Print the name and iterationsCount of each thread to show how many iterations each thread completed based on
their priority.
SOURCE CODE:
class PriorityThread extends Thread {
private int iterationsCount = 0;
public void run() {
for (int i = 0; i < 2000; i++) {
try {
Thread.sleep(1);
catch (InterruptedException e)
{
e.printStackTrace();
}
iterationsCount++;
System.out.println(Thread.currentThread().getName() + " - Iteration: " + i);
}
}
public int getIterationsCount() {
return iterationsCount;
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
PriorityThread highPriorityThread = new PriorityThread();
highPriorityThread.setName("High Priority Thread");
highPriorityThread.setPriority(Thread.MAX_PRIORITY);
PriorityThread normalPriorityThread = new PriorityThread();
normalPriorityThread.setName("Normal Priority Thread");
normalPriorityThread.setPriority(Thread.NORM_PRIORITY);
PriorityThread lowPriorityThread = new PriorityThread();
lowPriorityThread.setName("Low Priority Thread");
lowPriorityThread.setPriority(Thread.MIN_PRIORITY);
highPriorityThread.start();
normalPriorityThread.start();
lowPriorityThread.start();
try {
highPriorityThread.join();
normalPriorityThread.join();
lowPriorityThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\nThread Execution Counts:");
System.out.println(highPriorityThread.getName() + ": " +
highPriorityThread.getIterationsCount());
System.out.println(normalPriorityThread.getName() + ": " +
normalPriorityThread.getIterationsCount());
System.out.println(lowPriorityThread.getName() + ": " +
lowPriorityThread.getIterationsCount());
}
}
OUTPUT:
PROBLEM STATEMENT:
Part-B
Develop a multithreaded parking lot management system that allows cars to enter and exitconcurrently.
Requirements
ParkingLot Class:
Manage parking spaces using a Semaphore.
Methods:enterParkingLot(Car car): Car enters if space is available.
2. Car Class:exitParkingLot(Car car): Car exits, freeing a space.
Properties:
licensePlateowner
3. CarThread Class:
Simulate cars randomly entering and exiting the lot.
Extend Thread, with random stay times.
4. Simulation:
Run multiple car threads to test concurrent behavior.
5. Monitoring:
Track and display cars inside and available spaces.
6. Handle Exceptions:
Manage full parking lot and exit errors correctly.
EXTENCTION:
Adding two more methods and properties for the given question
DESCRIPTION:
Develop a multithreaded parking lot management system that allows cars to enter and exitconcurrently.
Requirements
1. ParkingLot Class:
Manage parking spaces using a Semaphore.o Methods:enterParkingLot(Car car): Car enters if space is available.
2. Car Class:
exitParkingLot(Car car): Car exits, freeing a space.o Properties:licensePlateowner
3. CarThread Class:
Simulate cars randomly entering and exiting the lot.o Extend Thread, with random stay times.
4. Simulation:
Run multiple car threads to test concurrent behavior.
5. Monitoring:
Track and display cars inside and available spaces.
6. Handle Exceptions:
Manage full parking lot and exit errors correctly.
ALGORITHM:
ParkingLot Class:
Initialize the parking lot with a specified number of spaces (totalSpaces).
2. Create a semaphore (availableSpaces) to manage available spaces.
3. Initialize currentCars to 0.
enterParkingLot Method:
1. Acquire a space using the semaphore (availableSpaces.acquire()).
2. Increment currentCars and display the updated count.
exitParkingLot Method:
1. Decrement currentCars and display the updated count.
2. Release a space using the semaphore (availableSpaces.release()).
CarThread Class:
1. Simulate a car entering the parking lot (parkingLot.enterParkingLot(car)).
2. Sleep for a random duration (up to 5 seconds) to simulate parking time.
3. Simulate the car exiting the parking lot (parkingLot.exitParkingLot(car)).
MonitorThread Class:
1. Periodically (every 2 seconds) display the available parking spaces.
SOURCE CODE:
import java.util.Random;
import java.util.concurrent.Semaphore;
class Car {
private String licensePlate;
private String owner;
public Car(String licensePlate, String owner) {
this.licensePlate = licensePlate;
this.owner = owner;
}
public String getLicensePlate() {
return licensePlate;
}
public String getOwner() {
return owner;
}}
class ParkingLot {
private final Semaphore availableSpaces;
private int totalSpaces;
private int currentCars;
public ParkingLot(int totalSpaces) {
this.totalSpaces = totalSpaces;
this.availableSpaces = new Semaphore(totalSpaces, true);
this.currentCars = 0;
}
public void enterParkingLot(Car car) {
try {
availableSpaces.acquire();
synchronized (this) {
currentCars++;
System.out.println(car.getLicensePlate() + " has entered the parking lot. Cars inside: " + currentCars);
}
}
catch (InterruptedException e) {
System.out.println("Failed to enter parking lot: " + car.getLicensePlate());
}
}
public void exitParkingLot(Car car) {
synchronized (this) {
if (currentCars > 0) {
currentCars--;
System.out.println(car.getLicensePlate() + " has exited the parking lot. Cars inside: " + currentCars);
availableSpaces.release();
} else {
System.out.println("Parking lot is empty. No cars to exit.");
}
}
}
public int getAvailableSpaces() {
return availableSpaces.availablePermits();
}}
class CarThread extends Thread {
private ParkingLot parkingLot;
private Car car;
private Random random;
public CarThread(ParkingLot parkingLot, Car car) {
this.parkingLot = parkingLot;
this.car = car;
this.random = new Random();
} @Override
public void run() {
try {
parkingLot.enterParkingLot(car);
Thread.sleep(random.nextInt(5000));
parkingLot.exitParkingLot(car);
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + car.getLicensePlate());
}
}}
class MonitorThread extends Thread[{
private ParkingLot parkingLot;
public MonitorThread(ParkingLot parkingLot) {
this.parkingLot = parkingLot;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(2000); // Check every 2 seconds
System.out.println("Available spaces: " + parkingLot.getAvailableSpaces());
} catch (InterruptedException e) {
System.out.println("Monitor thread interrupted.");
break;
}
}
}}
OUTPUT:
THANK YOU

THANK YOU

You might also like