CSW2 Assignment8 Soln
CSW2 Assignment8 Soln
(CHAPTER 19 – MULTITHREADING)
SOLUTIONS
--------------------------------------------------------------------------------
1. Write a Java program to demonstrate performing multiple tasks concurrently using
multiple threads. Create two separate thread classes:
• The first thread should calculate and print the sum of the first 100 natural numbers.
• The second thread should display the multiplication table of a given number Start
both threads from the main() method and show that the tasks run concurrently.
package q1;
class SumThread extends Thread {
public void run() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("SumThread interrupted");
}
}
System.out.println("Sum of first 100 natural numbers: " + sum);
}
}
class MultiplicationThread extends Thread {
private int number;
public MultiplicationThread(int number) {
this.number = number;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
try {
Thread.sleep(15);
} catch (InterruptedException e) {
System.out.println("MultiplicationThread interrupted");
}
}
}
}
public class MultiTask {
public static void main(String[] args) {
SumThread sumThread = new SumThread();
MultiplicationThread multiplicationThread = new MultiplicationThread(5);
sumThread.start();
multiplicationThread.start();
}
}
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Sum of first 100 natural numbers: 5050
package q2;
class AdditionThread extends Thread {
private int a, b;
public AdditionThread(int a, int b) {
this.a = a; this.b = b;
}
public void run() {
System.out.println("Addition: " + a + " + " + b + " = " + (a + b));
}
}
class SubtractionThread extends Thread {
private int a, b;
public SubtractionThread(int a, int b) {
this.a = a; this.b = b;
}
public void run() {
System.out.println("Subtraction: " + a + " - " + b + " = " + (a - b));
}
}
class MultiplicationThread extends Thread {
private int a, b;
public MultiplicationThread(int a, int b) {
this.a = a; this.b = b;
}
public void run() {
System.out.println("Multiplication: " + a + " * " + b + " = " + (a *
b));
}
}
class DivisionThread extends Thread {
private int a, b;
public DivisionThread(int a, int b) {
this.a = a; this.b = b;
}
public void run() {
if (b != 0) {
System.out.println("Division: " + a + " / " + b + " = " + ((double)
a / b));
} else {
System.out.println("Division: Cannot divide by zero.");
}
}
}
public class Calculator {
public static void main(String[] args) {
int num1 = 20, num2 = 5;
AdditionThread additionThread = new AdditionThread(num1, num2);
SubtractionThread subtractionThread = new SubtractionThread(num1, num2);
MultiplicationThread multiplicationThread = new
MultiplicationThread(num1, num2);
DivisionThread divisionThread = new DivisionThread(num1, num2);
additionThread.start();
subtractionThread.start();
multiplicationThread.start();
divisionThread.start();
}
}
Addition: 20 + 5 = 25
Multiplication: 20 * 5 = 100
Subtraction: 20 - 5 = 15
Division: 20 / 5 = 4.0
package q3;
public class CalculatorUsingLambda {
public static void main(String[] args) {
int num1 = 20;
int num2 = 5;
Thread addThread = new Thread(() -> {
System.out.println("Addition: " + num1 + " + " + num2 + " = " +
(num1 + num2));
});
Thread subtractThread = new Thread(() -> {
System.out.println("Subtraction: " + num1 + " - " + num2 + " = " +
(num1 - num2));
});
Thread multiplyThread = new Thread(() -> {
System.out.println("Multiplication: " + num1 + " * " + num2 + " = "
+ (num1 * num2));
});
Thread divideThread = new Thread(() -> {
if (num2 != 0) {
System.out.println("Division: " + num1 + " / " + num2 + " = " +
(num1 / num2));
} else {
System.out.println("Division by zero is not allowed.");
}
});
addThread.start();
subtractThread.start();
multiplyThread.start();
divideThread.start();
}
}
OUTPUT:
Addition: 20 + 5 = 25
Division: 20 / 5 = 4
Multiplication: 20 * 5 = 100
Subtraction: 20 - 5 = 15
package q4;
class MatrixMultiplierThread extends Thread {
private final int[][] A, B, result;
private final int row;
public MatrixMultiplierThread(int[][] A, int[][] B, int[][] result, int row)
{
this.A = A; this.B = B; this.result = result; this.row = row;
}
public void run() {
int colsB = B[0].length; int colsA = A[0].length;
for (int j = 0; j < colsB; j++) {
result[row][j] = 0;
for (int k = 0; k < colsA; k++) {
result[row][j] += A[row][k] * B[k][j];
}
}
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] A = {
{1, 2, 3},
{4, 5, 6}
};
int[][] B = {
{7, 8},
{9, 10},
{11, 12}
};
int rowsA = A.length;
int colsB = B[0].length;
int[][] result = new int[rowsA][colsB];
MatrixMultiplierThread[] threads = new MatrixMultiplierThread[rowsA];
for (int i = 0; i < rowsA; i++) {
threads[i] = new MatrixMultiplierThread(A, B, result, i);
threads[i].start();
}
for (int i = 0; i < rowsA; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Resultant Matrix:");
for (int[] row : result) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
OUTPUT:
Resultant Matrix:
58 64
139 154
package q5;
class Number {
private int num = 1; private final int limit;
public Number(int limit) {
this.limit = limit;
}
public synchronized void printOdd() {
while (num < limit) {
while (num % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd: " + num);
num++;
notify();
}
}
public synchronized void printEven() {
while (num <= limit) {
while (num % 2 != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even: " + num);
num++;
notify();
}
}
}
public class OddEven {
public static void main(String[] args) {
int limit = 10;
Number num = new Number(limit);
Thread oddThread = new Thread(num::printOdd);
Thread evenThread = new Thread(num::printEven);
oddThread.start();
evenThread.start();
}
}
OUTPUT:
Odd: 1
Even: 2
Odd: 3
Even: 4
Odd: 5
Even: 6
Odd: 7
Even: 8
Odd: 9
Even: 10
package q6;
class SeatBookingSystem {
private int availableSeats;
public SeatBookingSystem(int totalSeats) {
this.availableSeats = totalSeats;
}
public void bookSeats(String customerName, int seatsRequested) {
System.out.println(customerName + " is trying to book " + seatsRequested
+ " seat(s).");
synchronized (this) {
if (availableSeats >= seatsRequested) {
availableSeats -= seatsRequested;
System.out.println(customerName + " successfully booked " +
seatsRequested +
" seat(s). Remaining seats: " + availableSeats);
} else {
System.out.println("Booking failed for " + customerName +
". Not enough seats available. Remaining seats: " +
availableSeats);
}
}
}
}
public class SeatBookingDemo {
public static void main(String[] args) {
SeatBookingSystem bookingSystem = new SeatBookingSystem(5);
Object[][] customers = {
{"Cust 1", 2},
{"Cust 2", 1},
{"Cust 3", 2},
{"Cust 4", 1}
};
for (Object[] customer : customers) {
String name = (String) customer[0];
int seats = (int) customer[1];
Thread thread = new Thread(() -> bookingSystem.bookSeats(name,
seats), name);
thread.start();
}
}
}
OUTPUT:
package q7;
import java.util.ArrayList;
import java.util.List;
class PrimeCalculator extends Thread {
private final int start, end;
private final List<Integer> primes;
public PrimeCalculator(int start, int end, List<Integer> primes) {
this.start = start;
this.end = end;
this.primes = primes;
}
private boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
public void run() {
for (int num = start; num <= end; num++) {
if (isPrime(num)) {
synchronized (primes) {
primes.add(num);
}
}
}
}
}
public class PrimeNumber {
public static void main(String[] args) {
int limit = 50;
int numThreads = 4;
List<Integer> primes = new ArrayList<>();
Thread[] threads = new Thread[numThreads];
int range = limit / numThreads;
for (int i = 0; i < numThreads; i++) {
int start = i * range + 1;
int end = (i == numThreads - 1) ? limit : (i + 1) * range;
threads[i] = new PrimeCalculator(start, end, primes);
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
primes.sort(Integer::compareTo);
System.out.println("Prime numbers up to " + limit + ": " + primes);
}
}
OUTPUT:
Prime numbers up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
package q8;
import java.util.LinkedList;
import java.util.Queue;
class SharedBuffer {
private final Queue<Integer> buffer = new LinkedList<>();
private final int capacity;
public SharedBuffer(int capacity) {
this.capacity = capacity;
}
public synchronized void put(int value) {
while (buffer.size() == capacity) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.offer(value);
System.out.println("Produced: " + value);
notify();
}
public synchronized int get() {
while (buffer.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int value = buffer.poll();
System.out.println("Consumed: " + value);
notify(); return value;
}
}
class Producer extends Thread {
private final SharedBuffer buffer;
public Producer(SharedBuffer buffer) {
this.buffer = buffer;
}
public void run() {
for (int i = 1; i <= 5; i++) {
buffer.put(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
OUTPUT:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Consumed: 5
Producer and Consumer have completed their tasks.