0% found this document useful (0 votes)
9 views13 pages

Object Oriented Programming Using Java Laboratory (DJS23FLES201) F.Y B. Tech Semester: II Experiment No-13

The document outlines a laboratory experiment for F.Y B. Tech students focusing on Object Oriented Programming using Java, specifically multithreading. It includes multiple programming tasks such as printing multiplication tables, displaying patterns, generating Fibonacci sequences, preventing concurrent ticket bookings, and demonstrating various thread methods. Each task is accompanied by code examples and conclusions emphasizing the learning outcomes related to multithreading in Java.
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)
9 views13 pages

Object Oriented Programming Using Java Laboratory (DJS23FLES201) F.Y B. Tech Semester: II Experiment No-13

The document outlines a laboratory experiment for F.Y B. Tech students focusing on Object Oriented Programming using Java, specifically multithreading. It includes multiple programming tasks such as printing multiplication tables, displaying patterns, generating Fibonacci sequences, preventing concurrent ticket bookings, and demonstrating various thread methods. Each task is accompanied by code examples and conclusions emphasizing the learning outcomes related to multithreading in Java.
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/ 13

Object Oriented Programming using Java Laboratory (DJS23FLES201)

F.Y B. Tech Semester: II


(Academic Year 2024-25)
Experiment No-13

Name: Krish B Parmar SAP ID: 60019240112 Roll No:B032

Branch: CS(ICB) Div: B Batch:B-1

Aim: a. Write a multithreaded program a java program to print Table of Five, Seven and
Thirteen using Multithreading (Use Thread class for the implementation).

Program Code:
class TablePrinter extends Thread {
private int number;
public TablePrinter(int number) {
this.number = number;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}

public static void main(String[] args) {


TablePrinter tableOfFive = new TablePrinter(5);
TablePrinter tableOfSeven = new TablePrinter(7);
TablePrinter tableOfThirteen = new TablePrinter(13);

tableOfFive.start();
tableOfSeven.start();
tableOfThirteen.start();
}
}
Program output:

Conclusion: By implementing the above program we got to learn how to handle the multithreading and
how we can use them in different java codes to easily find the solution of a given program.
b. Write a multithreaded program to display /*/*/*/*/*/*/*/* using 2 child threads.
Program code:
public class MultiThreadPattern {
public static void main(String[] args) {
Printer printer = new Printer();
Thread thread1 = new Thread(new PatternTask(printer), "Thread-1");
Thread thread2 = new Thread(new PatternTask(printer), "Thread-2");

thread1.start();
thread2.start();
}
}
class Printer {
private int count = 0;
private final int MAX = 8;
// synchronized method to avoid race condition
public synchronized void printPattern() {
while (count < MAX) {
System.out.print("/*");
count++;
notify(); // wake up the other thread
try {
if (count < MAX)
wait(); // wait only if more prints needed
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class PatternTask implements Runnable {
private final Printer printer;
public PatternTask(Printer printer) {
this.printer = printer;
}
@Override
public void run() {
printer.printPattern();
}
}
Program output:

Conclusion: By implementing the above program we got to learn how to handle the multithreading and
how we can use them in different java codes to easily find the solution of a given program like printing a
pattern.
c. Write a multithreaded program that generates the Fibonacci sequence. This program should
work as follows: create a class Input that reads the number of Fibonacci numbers that the program
is to generate. The class will then create a separate thread that will generate the Fibonacci numbers,
placing the sequence in an array. When the thread finishes execution, the parent thread (Input class)
will output the sequence generated by the child thread. Because the parent thread cannot begin
outputting the Fibonacci sequence until the child thread finishes, the parent thread will have to wait
for the child thread to finish.

Program code:
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter how many Fibonacci numbers to generate: ");
int n = scanner.nextInt();
// Create and start the Fibonacci thread
FibonacciGenerator generator = new FibonacciGenerator(n);
Thread fibThread = new Thread(generator);
fibThread.start();
try {
// Wait for the Fibonacci thread to finish
fibThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
// Output the generated sequence
int[] sequence = generator.getSequence();
System.out.print("Fibonacci sequence: ");
for (int num : sequence) {
System.out.print(num + " ");
}
}
}

// Child thread to generate Fibonacci numbers


class FibonacciGenerator implements Runnable {
private final int count;
private final int[] sequence;

public FibonacciGenerator(int count) {


this.count = count;
this.sequence = new int[count];
}

@Override
public void run() {
if (count > 0) sequence[0] = 0;
if (count > 1) sequence[1] = 1;

for (int i = 2; i < count; i++) {


sequence[i] = sequence[i - 1] + sequence[i - 2];
}
}
public int[] getSequence() {
return sequence;
}
}
Program output:

Conclusion: By implementing the above program we got to learn how to handle the multithreading and
how we can use them in different java codes to easily find the solution of a given program.
d. WAP to prevent concurrent booking of a ticket using the concept of thread synchronization.

Program code:
class TicketBooking {
private boolean isBooked = false;
// Synchronized method to prevent concurrent booking
public synchronized void bookTicket(String userName) {
if (!isBooked) {
System.out.println(userName + " is booking the ticket...");
try {
Thread.sleep(1000); // Simulate time taken for booking
} catch (InterruptedException e) {
e.printStackTrace();
}
isBooked = true;
System.out.println("Ticket successfully booked by " + userName);
} else {
System.out.println("Sorry " + userName + ", ticket already booked!");
}
}
}
class User extends Thread {
private final TicketBooking booking;
private final String userName;
public User(TicketBooking booking, String userName) {
this.booking = booking;
this.userName = userName;
}
@Override
public void run() {
booking.bookTicket(userName);
}
}
public class TicketBookingSystem {
public static void main(String[] args) {
TicketBooking booking = new TicketBooking();
// Create multiple users trying to book the same ticket
User user1 = new User(booking, "Alice");
User user2 = new User(booking, "Bob");
User user3 = new User(booking, "Charlie");
user1.start();
user2.start();
user3.start();
}
}

Program output:

Conclusion: By implementing the above program we got to learn how to handle the
multithreading and how we can use them in different java codes to easily find the solution of
a given program.
e. Write a program to demonstrate thread methods: wait notify suspend resume join setpriority
getpriority setname getname

Program code:
class SharedResource {
synchronized void waitAndNotifyDemo() {
System.out.println(Thread.currentThread().getName() + " is inside
waitAndNotifyDemo...");
try {
wait(); // Current thread waits
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " resumed after notify.");
}
synchronized void triggerNotify() {
System.out.println(Thread.currentThread().getName() + " is notifying waiting
thread...");
notify(); // Notify one waiting thread
}
}
class MyThread extends Thread {
SharedResource resource;
public MyThread(String name, SharedResource resource) {
super(name); // setName()
this.resource = resource;
}

@Override
public void run() {
System.out.println(getName() + " started with priority " + getPriority());

if (getName().equals("Waiter")) {
resource.waitAndNotifyDemo();
} else if (getName().equals("Notifier")) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.triggerNotify();
}
}
}

public class ThreadMethodsDemo {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

MyThread waiter = new MyThread("Waiter", resource);


MyThread notifier = new MyThread("Notifier", resource);

waiter.setPriority(Thread.MAX_PRIORITY);
notifier.setPriority(Thread.MIN_PRIORITY);

waiter.start();
notifier.start();

try {
waiter.join();
notifier.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

Thread suspendedThread = new Thread(() -> {


System.out.println("SuspendedThread is running...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("SuspendedThread completed.");
});
suspendedThread.setName("SuspendedThread");
System.out.println("Starting " + suspendedThread.getName());
suspendedThread.start();
try {
Thread.sleep(1000);
System.out.println("Suspending (deprecated) " + suspendedThread.getName());
Thread.sleep(2000);
System.out.println("Resuming (deprecated) " + suspendedThread.getName());
suspendedThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Main thread completed.");


}
}
Program code:

Conclusion: By implementing the above program we got to learn how to handle the
multithreading and how we can use them in different java codes to easily find the solution of
a given program

You might also like