Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Assignment 2

The document outlines multiple programming assignments related to multithreading in Java. It includes tasks such as creating threads to print text, implementing a countdown, solving the producer-consumer problem, calculating sums and averages using multiple threads, and developing a simple search engine. Each task is accompanied by sample code demonstrating the implementation of the required functionality.

Uploaded by

sonyabhongale11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Assignment 2

The document outlines multiple programming assignments related to multithreading in Java. It includes tasks such as creating threads to print text, implementing a countdown, solving the producer-consumer problem, calculating sums and averages using multiple threads, and developing a simple search engine. Each task is accompanied by sample code demonstrating the implementation of the required functionality.

Uploaded by

sonyabhongale11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Assignment 2:Multithreading

Set A
a) Program in define a thread for printing text on output screen for 'n' sumber
of times. Create 3 threads and run them. Pass the text 'n' parameters to the
thread constructor.

Example

First thread prints "COVID19" 10 times.

Second thread prints "LOCKDOWN2020 20 times

Third thread prints "VACCINATED2021" 30 times

Program:-

// Create a custom thread class

class PrintTextThread extends Thread {

private String text;

private int n;

// Constructor to initialize text and number of repetitions

public PrintTextThread(String text, int n) {

this.text = text;

this.n = n;

// Override the run method to print text 'n' times

@Override

public void run() {

1
for (int i = 0; i < n; i++) {

System.out.println(text);

public class Main {

public static void main(String[] args) {

// Create 3 threads with different texts and repetition counts

PrintTextThread thread1 = new PrintTextThread("COVID19", 10);

PrintTextThread thread2 = new PrintTextThread("LOCKDOWN2020", 20);

PrintTextThread thread3 = new PrintTextThread("VACCINATED2021", 30);

// Start the threads

thread1.start();

thread2.start();

thread3.start();

try {

// Wait for all threads to finish

thread1.join();

thread2.join();

thread3.join();

} catch (InterruptedException e) {

2
System.out.println("Thread interrupted");

System.out.println("All threads have finished printing.");

}}

Outpot:-

3
b) Write a program in which themad sleep for 6 sec in the loop in reverse order
from 100 to 1 and change the name of thread.

Program:-

class CountdownThread extends Thread {

public CountdownThread(String name) {

// Set the name of the thread

super(name);

@Override

public void run() {

for (int i = 100; i >= 1; i--) {

try {

// Print the current thread name and the countdown number

System.out.println(getName() + " - " + i);

// Sleep for 6 seconds (6000 milliseconds)

Thread.sleep(6000);

// Change the name of the thread dynamically

setName("Thread #" + i);

} catch (InterruptedException e) {

System.out.println(getName() + " was interrupted.");

4
}

public class Main1 {

public static void main(String[] args) {

// Create the thread and start it

CountdownThread countdownThread = new CountdownThread("InitialThread");

countdownThread.start();

}Outpot:-

5
6
c)Write a program to solve producer consumer problem in which a producer
produces a value and consumer consume the value before producer generate
the next value.

(Hint: use thread synchronization)

Program:-

class SharedBuffer {

private int value;

private boolean isValueProduced = false;

// Synchronized method to produce a value

public synchronized void produce(int value) throws InterruptedException {

while (isValueProduced) {

wait(); // Wait if a value is already produced (buffer is full)

this.value = value;

isValueProduced = true; // Mark that a value is produced

System.out.println("Produced: " + value);

notify(); // Notify the consumer that a value is available

// Synchronized method to consume a value

public synchronized int consume() throws InterruptedException {

while (!isValueProduced) {

wait(); // Wait if no value has been produced (buffer is empty)

7
isValueProduced = false; // Mark that the value is consumed

System.out.println("Consumed: " + value);

notify(); // Notify the producer that the buffer is empty

return value;

class Producer extends Thread {

private SharedBuffer buffer;

public Producer(SharedBuffer buffer) {

this.buffer = buffer;

@Override

public void run() {

int i = 1;

while (true) {

try {

buffer.produce(i); // Produce a new value

i++; // Increment the value to be produced

Thread.sleep(1000); // Simulate time taken to produce the value

} catch (InterruptedException e) {

System.out.println("Producer interrupted.");

8
}

class Consumer extends Thread {

private SharedBuffer buffer;

public Consumer(SharedBuffer buffer) {

this.buffer = buffer;

@Override

public void run() {

while (true) {

try {

int value = buffer.consume(); // Consume the produced value

Thread.sleep(2000); // Simulate time taken to consume the value

} catch (InterruptedException e) {

System.out.println("Consumer interrupted.");

9
public class Main {

public static void main(String[] args) {

// Create the shared buffer

SharedBuffer buffer = new SharedBuffer();

// Create the producer and consumer threads

Producer producer = new Producer(buffer);

Consumer consumer = new Consumer(buffer);

// Start the threads

producer.start();

consumer.start();

Outpot:-

10
Set B
a) Write a program to calculate the sum and average of an array of 1000
integers (generated randomly) using 10 threads. Each thread calculates
the sum of 100 integers. Use these values to calculate average. [Use join
method ].

Program:-

import java.util.Random;

class SumTask extends Thread {

private int[] array;

private int start;

private int end;

private long sum;

public SumTask(int[] array, int start, int end) {

this.array = array;

this.start = start;

this.end = end;

this.sum = 0;

@Override

public void run() {

// Calculate the sum for the segment of the array

11
for (int i = start; i < end; i++) {

sum += array[i];

public long getSum() {

return sum;

public class Main {

public static void main(String[] args) throws InterruptedException {

// Generate an array of 1000 random integers

int[] array = new int[1000];

Random random = new Random();

for (int i = 0; i < array.length; i++) {

array[i] = random.nextInt(100); // Random integers between 0 and 99

// Create 10 threads to calculate the sum of 100 integers each

SumTask[] tasks = new SumTask[10];

for (int i = 0; i < 10; i++) {

int start = i * 100;

int end = (i + 1) * 100;

12
tasks[i] = new SumTask(array, start, end);

tasks[i].start();

// Wait for all threads to finish and calculate the total sum

long totalSum = 0;

for (int i = 0; i < 10; i++) {

tasks[i].join(); // Wait for each thread to finish

totalSum += tasks[i].getSum();

// Calculate the average

double average = totalSum / 1000.0;

// Output the results

System.out.println("Total Sum: " + totalSum);

System.out.println("Average: " + average);

Outpot:-

13
b) Write a program for a simple search engine. Accept a string to be
searched. Search for the string in all text files in the current folder. Use a
separate thread for each file. The result should display the filename, line
number where the string is found.

Program:-

import java.io.*;

import java.util.*;

import java.util.concurrent.*;

class SearchTask extends Thread {

private String filename;

private String searchString;

public SearchTask(String filename, String searchString) {

this.filename = filename;

this.searchString = searchString;

@Override

public void run() {

try (BufferedReader reader = new BufferedReader(new


FileReader(filename))) {

String line;

int lineNumber = 1;

boolean found = false;

14
while ((line = reader.readLine()) != null) {

if (line.contains(searchString)) {

if (!found) {

System.out.println("In file: " + filename);

found = true;

System.out.println("Line " + lineNumber + ": " + line);

lineNumber++;

} catch (IOException e) {

System.out.println("Error reading file: " + filename);

public class SimpleSearchEngine {

public static void main(String[] args) throws InterruptedException {

Scanner scanner = new Scanner(System.in);

// Ask for search string

System.out.print("Enter the string to search: ");

String searchString = scanner.nextLine();

15
// List all text files in the current directory

File currentDir = new File(".");

File[] files = currentDir.listFiles((dir, name) -> name.endsWith(".txt"));

if (files == null || files.length == 0) {

System.out.println("No text files found in the current directory.");

return;

// Create an executor to manage threads

ExecutorService executor = Executors.newFixedThreadPool(files.length);

// Create and submit a task for each file

for (File file : files) {

SearchTask task = new SearchTask(file.getName(), searchString);

executor.submit(task);

// Shut down the executor once all tasks are completed

executor.shutdown();

executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

scanner.close();

16
Outpot:-

c) Write a program that implements a multi-thread application that has


three threads. First thread generates random integer every 1 second and
if the value is even, second thread computes the square of the number
and prints. If the value is odd, the third thread will print the value of cube
of the number.

Program:-

import java.util.Random;

class RandomNumberGenerator extends Thread {

private SharedData sharedData;

public RandomNumberGenerator(SharedData sharedData) {

this.sharedData = sharedData;

@Override

public void run() {

Random random = new Random();

while (true) {

try {

17
// Generate a random integer between 1 and 100

int number = random.nextInt(100) + 1;

System.out.println("Generated: " + number);

synchronized (sharedData) {

sharedData.setNumber(number); // Set the number in shared data

sharedData.notifyAll(); // Notify other threads to process the number

Thread.sleep(1000); // Wait for 1 second before generating the next


number

} catch (InterruptedException e) {

e.printStackTrace();

class EvenNumberProcessor extends Thread {

private SharedData sharedData;

public EvenNumberProcessor(SharedData sharedData) {

this.sharedData = sharedData;

18
@Override

public void run() {

while (true) {

synchronized (sharedData) {

try {

while (sharedData.getNumber() == -1) {

sharedData.wait(); // Wait for a number to be generated

int number = sharedData.getNumber();

if (number % 2 == 0) {

int square = number * number;

System.out.println("Even Thread: Square of " + number + " is " +


square);

sharedData.setNumber(-1); // Reset the number to indicate that it


has been processed

} catch (InterruptedException e) {

e.printStackTrace();

19
class OddNumberProcessor extends Thread {

private SharedData sharedData;

public OddNumberProcessor(SharedData sharedData) {

this.sharedData = sharedData;

@Override

public void run() {

while (true) {

synchronized (sharedData) {

try {

while (sharedData.getNumber() == -1) {

sharedData.wait(); // Wait for a number to be generated

int number = sharedData.getNumber();

if (number % 2 != 0) {

int cube = number * number * number;

System.out.println("Odd Thread: Cube of " + number + " is " +


cube);

20
sharedData.setNumber(-1); // Reset the number to indicate that it
has been processed

} catch (InterruptedException e) {

e.printStackTrace();

class SharedData {

private int number = -1; // -1 means no number has been generated yet

public int getNumber() {

return number;

public void setNumber(int number) {

this.number = number;

public class Main {

public static void main(String[] args) {

SharedData sharedData = new SharedData();

21
// Create the threads

RandomNumberGenerator generator = new


RandomNumberGenerator(sharedData);

EvenNumberProcessor evenProcessor = new


EvenNumberProcessor(sharedData);

OddNumberProcessor oddProcessor = new


OddNumberProcessor(sharedData);

// Start the threads

generator.start();

evenProcessor.start();

oddProcessor.start();

Outpot:-

22
23

You might also like