C9Lab 11 Final
C9Lab 11 Final
238W1A05C9
Lab Session 11
Apply the concepts of Threads and Multithreading on a given application
Date of the Session:1/11/2024 Time of the Session:10:20 AM – 1:00 PM
Pre-Lab Tasks:
1. Mention two ways in which thread can be created.
1. Write a java program using multithreading in which each thread reads the data from a text file and
displays the data of each file on Console alternatively such that one line from first input file is printed
and then one line from another input file is printed and so on.
You are required to develop a java program containing two threads that reads two files simultaneously.
In a program, first thread reads data from file “PersonalRecord.txt” and second thread reads the data
from file “AcademicRecord.txt”. When one thread reads a line from one file then it should allow
another thread to read a line from another file. After reading data from each file, program must write
the output on console (Output screen) such that one line from first input file is printed and then one
line from another input file is printed and so on.
Test Case:
Input:
PersonalRecord.txt
AcademicRecord.txt
Output:
Thread 1:Ajay
Thread 2:DBMS - 96
Thread 2:DLD - 92
Thread 1:9988776655
Thread 2:Java - 95
Thread 1:[email protected]
Thread 2:Data Structures - 94
Thread 1:Vijayawada, Andhra Pradesh
Source Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new
FileReader(fileName))) {
String line;
try {
lock.wait(); // Wait for the other thread to print its
line
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
synchronized (lock) { // Ensures no thread is left waiting
lock.notify();
}
} catch (IOException e) {
System.err.println("Error reading from file: " +
e.getMessage());
}
}
}
thread1.setName("Thread 1");
thread2.setName("Thread 2");
thread1.start();
thread2.stop();
}
}
Output:
Result:
The program to Develop an algorithm to read two text files
concurrently using separate threads, has been executed and run
successfully.
Post-Lab Tasks:
1. Write a program based on performing multiple tasks with a single thread. Task 1 is to perform addition,
Task 2 is to perform subtraction, and Task 3 is to perform multiplication when numbers are given as
20 and 10.
Test Cases:
Output:
Main thread running
Addition of two numbers: 30
Subtraction of two numbers: 10
Multiplication of two numbers: 200
Main thread exiting
Souce Code:
// Task 1: Addition
// Task 2: Subtraction
// Task 3: Multiplication
return a + b;
return a - b;
return a * b;
}
Output:
Result:
The program to Develop an algorithm to use arithmetic operations
(addition, subtraction, and multiplication) on two user-provided
integers using multiple threads. separate threads, has been
executed and run successfully.
Student’s Signature
Faculty Signature