0% found this document useful (0 votes)
11 views19 pages

22MIC0044JAVA

The document provides instructions for 5 programming assignments involving threads. The first few assignments involve creating thread classes that print messages or tables. The last two assignments create threads that deposit and withdraw from a bank account, demonstrating synchronized and wait/notify access.
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)
11 views19 pages

22MIC0044JAVA

The document provides instructions for 5 programming assignments involving threads. The first few assignments involve creating thread classes that print messages or tables. The last two assignments create threads that deposit and withdraw from a bank account, demonstrating synchronized and wait/notify access.
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/ 19

SLOT – L53+L54

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING


CYCLE SHEET – II – WINTER SEMESTER 2023-2024
Programme Name & Branch: B.Tech (CSE) Course Name: Java Programming Lab
Course Code: CSI2008
Note : Upload Source Code with Output screen in VTOP

CYCLE SHEET -2
1. Create a Thread class with name "GreetThread" and override the run method to say
greeting message for 5 Times. Create Two objects of the thread and start each of such
thread objects.

SOURCE CODE:

class CustomGreetingThread extends Thread {


@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Custom Greeting from Thread " + Thread.currentThread().getName());
try {
Thread.sleep(800); // Changed sleep time for variation
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class CustomGreetings {


public static void main(String[] args) {
CustomGreetingThread thread1 = new CustomGreetingThread();
thread1.setName("Alpha");
thread1.start();

CustomGreetingThread thread2 = new CustomGreetingThread();


thread2.setName("Beta");
thread2.start();
}
}OUTPUT:
2. Modify the above thread class such that that would say Greetings message added with
any name passed through the parameter in its constructor. and use the name to say
greetings. Create Two objects of the thread and start each of such thread objects with
different name passed through the constructor

SOURCE CODE:

class CustomGreetThread extends Thread {


private String name;

public CustomGreetThread(String name) {


this.name = name;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Greetings from " + name + "'s Thread");
try {
Thread.sleep(1200); // Changed sleep time for variation
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class CustomGreetings {


public static void main(String[] args) {
CustomGreetThread thread1 = new CustomGreetThread("Thara");
thread1.start();

CustomGreetThread thread2 = new CustomGreetThread("Brownie");


thread2.start();
}
}

OUTPUT:
3. Create a Class name AddTable that will implement a method printTable(int n) to print first
5 entries of nth ADDITION table. Try to create a thread class that overides the run() method
and then calls the printTable(int n) method throgh the objects of the display class. Create
two thread objects such that one will print 5th Table and other one will print 7th Table.
Demonstrate the execution of the threads with synchronized and without synchronized
keyword.

SOURCE CODE:

class AdditionTablePrinter {
synchronized void printTable(int n) {
System.out.println("Printing the first 5 entries of the " + n + "th Addition Table:");
for (int i = 1; i <= 5; i++) {
System.out.println(n + " + " + i + " = " + (n + i));
}
System.out.println();
}
}

class TablePrintingThread extends Thread {


private AdditionTablePrinter tablePrinter;
private int n;

public TablePrintingThread(AdditionTablePrinter tablePrinter, int n) {


this.tablePrinter = tablePrinter;
this.n = n;
}

@Override
public void run() {
tablePrinter.printTable(n);
}
}
public class SynchronizedTablePrinting {
public static void main(String[] args) {
AdditionTablePrinter tablePrinter = new AdditionTablePrinter();

System.out.println("Without Synchronization:");
TablePrintingThread thread1 = new TablePrintingThread(tablePrinter, 5);
TablePrintingThread thread2 = new TablePrintingThread(tablePrinter, 7);
thread1.start();
thread2.start();

try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("With Synchronization:");
TablePrintingThread synchronizedThread1 = new TablePrintingThread(tablePrinter, 5);
TablePrintingThread synchronizedThread2 = new TablePrintingThread(tablePrinter, 7);
synchronizedThread1.start();
synchronizedThread2.start();
}
}
OUTPUT:
4. With the help of two separate thread , implement the following formula to determine

SOURCE CODE:

class PartialSumCalculator extends Thread {


private int[] values;
private int[] frequencies;
private int startIndex;
private int endIndex;
private double partialSum;

public PartialSumCalculator(int[] values, int[] frequencies, int startIndex, int endIndex) {


this.values = values;
this.frequencies = frequencies;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.partialSum = 0;
}

public double getPartialSum() {


return partialSum;
}

@Override
public void run() {
for (int i = startIndex; i < endIndex; i++) {
partialSum += values[i] * frequencies[i];
}
}
}

public class MeanCalculatorApp {


public static void main(String[] args) {
int[] values = {10, 20, 30, 40, 50};
int[] frequencies = {2, 3, 4, 5, 6};
int numThreads = 3;

PartialSumCalculator[] threads = new PartialSumCalculator[numThreads];


int chunkSize = values.length / numThreads;
int startIndex = 0;
int endIndex = 0;

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


startIndex = endIndex;
endIndex = Math.min(startIndex + chunkSize, values.length);
threads[i] = new PartialSumCalculator(values, frequencies, startIndex, endIndex);
threads[i].start();
}

double totalSum = 0;
try {
for (PartialSumCalculator thread : threads) {
thread.join();
totalSum += thread.getPartialSum();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

double mean = totalSum / sumArray(frequencies);

System.out.println("Calculated Mean: " + mean);


}

private static int sumArray(int[] array) {


int sum = 0;
for (int num : array) {
sum += num;
}
return sum;
}
}
OUTPUT:

Q5. Create a BankAccount class that would implement deposit(int amount) and withdraw(int
amount) and also declare the instance variables such as accno, accountname and balance

Create an object of this account and pass it to two separate threads such that one is invoking
deposit() method meanwhile other one is invoking withdraw() method. Demonstrate the
execution of the threads with synchronized and without synchronized keyword.

Use wait() and notify() method to be implemented over the BankAccount object . Assume that
this account is jointly used by both parent and his son . The son thread has to wait if there is
no available money to withdraw . Meanwhile if parent thread sends notification to wake of
the son thread once amount is deposited into the account

SOURCE CODE:

class BankAccount {
private int accountNumber;
private String accountHolderName;
private int balance;

public BankAccount(int accountNumber, String accountHolderName, int balance) {


this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

synchronized void deposit(int amount) {


balance += amount;
System.out.println("Deposited " + amount + " rupees. New balance: " + balance);
}

synchronized void withdraw(int amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn " + amount + " rupees. New balance: " + balance);
} else {
System.out.println("Insufficient balance.");
}
}
}

class DepositTask extends Thread {


private BankAccount account;
private int amount;

public DepositTask(BankAccount account, int amount) {


this.account = account;
this.amount = amount;
}

@Override
public void run() {
account.deposit(amount);
}
}

class WithdrawTask extends Thread {


private BankAccount account;
private int amount;

public WithdrawTask(BankAccount account, int amount) {


this.account = account;
this.amount = amount;
}

@Override
public void run() {
account.withdraw(amount);
}
}

public class SynchronizedBankTransactions {


public static void main(String[] args) {
BankAccount account = new BankAccount(123456, "John Doe", 1000);

System.out.println("Without Synchronization:");
DepositTask depositTask = new DepositTask(account, 500);
WithdrawTask withdrawTask = new WithdrawTask(account, 200);
depositTask.start();
withdrawTask.start();

try {
depositTask.join();
withdrawTask.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("With Synchronization:");
DepositTask synchronizedDepositTask = new DepositTask(account, 500);
WithdrawTask synchronizedWithdrawTask = new WithdrawTask(account, 200);
synchronizedDepositTask.start();
synchronizedWithdrawTask.start();
}
}

OUTPUT:

SOURCE CODE:

class BankAccount {
private int accno;
private String accountName;
private int balance;

public BankAccount(int accno, String accountName, int balance) {


this.accno = accno;
this.accountName = accountName;
this.balance = balance;
}

synchronized void deposit(int amount) {


balance += amount;
System.out.println("Deposited " + amount + " rupees. New balance: " + balance);

notify();
}

synchronized void withdraw(int amount) {


while (balance < amount) {
try {

System.out.println("Son: Insufficient balance. Waiting for deposit...");


wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance -= amount;
System.out.println("Son: Withdrawn " + amount + " rupees. New balance: " + balance);
}
}

class ParentThread extends Thread {


private BankAccount account;
private int amount;

public ParentThread(BankAccount account, int amount) {


this.account = account;
this.amount = amount;
}

@Override
public void run() {
account.deposit(amount);
}
}

class SonThread extends Thread {


private BankAccount account;
private int amount;

public SonThread(BankAccount account, int amount) {


this.account = account;
this.amount = amount;
}

@Override
public void run() {
account.withdraw(amount);
}
}

public class Main {


public static void main(String[] args) {
BankAccount account = new BankAccount(123456, "Joint Account", 1000);

ParentThread parentThread = new ParentThread(account, 500);


parentThread.start();

SonThread sonThread = new SonThread(account, 200);


sonThread.start();
}
}

OUTPUT:

Q6. Write the following data to a datafile item.dat and again read it and find out the total
amount paid by the all customers.

double[] Cost = { 15.43, 10.12, 50.8, 249.56, 18.99 };

int[] quantity = { 10, 23, 45, 14, 2 };


String[] items = { "P101", "P201", "P123", "P453", "P864" };

SOURCE CODE:
import java.io.*;

public class ItemDataProcessing {

public static void main(String[] args) {

double[] cost = { 15.43, 10.12, 50.8, 249.56, 18.99 };


int[] quantity = { 10, 23, 45, 14, 2 };
String[] items = { "P101", "P201", "P123", "P453", "P864" };

writeDataToFile("item.dat", cost, quantity, items);

double totalAmountPaid = calculateTotalAmount("item.dat");


System.out.println("Total amount paid by all customers: Rupees " + totalAmountPaid);
}

private static void writeDataToFile(String fileName, double[] cost, int[] quantity, String[] items) {
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName))) {
for (int i = 0; i < cost.length; i++) {
out.writeDouble(cost[i]); // Write double instead of float
out.writeInt(quantity[i]);
out.writeUTF(items[i]);
}
System.out.println("Data written to " + fileName);
} catch (IOException e) {
System.err.println("Error writing data to file: " + e.getMessage());
}
}

private static double calculateTotalAmount(String fileName) {


double totalAmount = 0.0;
try (DataInputStream in = new DataInputStream(new FileInputStream(fileName))) {
while (in.available() > 0) {
double itemCost = in.readDouble(); // Read double instead of float
int itemQuantity = in.readInt();
in.readUTF(); // Skipping reading the item name as it's not needed for calculation
double itemAmount = itemCost * itemQuantity;
totalAmount += itemAmount;
}
} catch (IOException e) {
System.err.println("Error reading data from file: " + e.getMessage());
}
return totalAmount;
}
}

OUTPUT:

Q7. Write a Java Program to create two threads such that one thread uses to push the uppercase
letters of a sentence onto a piped output stream and another thread pull the data through the
piped input stream and converts all received letters into lowercase letters.

SOURCE CODE:

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;

class UppercaseThread extends Thread {


private PipedOutputStream pipedOutputStream;
private String sentence;

public UppercaseThread(PipedOutputStream pipedOutputStream, String sentence) {


this.pipedOutputStream = pipedOutputStream;
this.sentence = sentence;
}

public void run() {


try {
for (char c : sentence.toCharArray()) {
if (Character.isUpperCase(c)) {
pipedOutputStream.write(c);
}
}
pipedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

class LowercaseThread extends Thread {


private PipedInputStream pipedInputStream;

public LowercaseThread(PipedInputStream pipedInputStream) {


this.pipedInputStream = pipedInputStream;
}

public void run() {


try {
int data;
while ((data = pipedInputStream.read()) != -1) {
char c = (char) data;
char lowercase = Character.toLowerCase(c);
System.out.print(lowercase);
}
pipedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public class PipedStreamExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
scanner.close();

try {
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

UppercaseThread uppercaseThread = new UppercaseThread(pipedOutputStream, sentence);


LowercaseThread lowercaseThread = new LowercaseThread(pipedInputStream);

uppercaseThread.start();
lowercaseThread.start();

uppercaseThread.join();
lowercaseThread.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}

OUTPUT:

Q8. Assume that you have two text files that stored the following details . The first text file stores
text A and second file stores Text B

Read all the files one by one and count the frequency count of each word together with all files using
sequence input stream.

SOURCE CODE:

import java.io.*;
import java.util.*;
public class WordFrequencyCounter {

public static void main(String[] args) {

Map<String, Integer> wordFrequencyMap = new HashMap<>();

processFile("file1.txt", wordFrequencyMap);
processFile("file2.txt", wordFrequencyMap);

System.out.println("Word Frequencies Across Both Files:");


for (Map.Entry<String, Integer> entry : wordFrequencyMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}

private static void processFile(String filename, Map<String, Integer> wordFrequencyMap) {


try (Scanner scanner = new Scanner(new File(filename))) {

while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();

wordFrequencyMap.put(word, wordFrequencyMap.getOrDefault(word, 0) + 1);


}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + filename);
}
}
}

FILE 1:

FILE 2:

OUTPUT:
Q9. Define a class “Customer” with following members where as the objects of this class could be
serializabe onto a file. Create 5 different objects of customer and seralize them into a file with
“youregno.ser”. During serialization you should mask the value of the gender. After that deserialize
the count of customers whose name started “Ram”..

SOURCE CODE:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

class Customer implements Serializable {


private static final long serialVersionUID = 1L;

private int id;


private String name;
private char gender;

public Customer(int id, String name, char gender) {


this.id = id;
this.name = name;
this.gender = gender;
}

public int getId() {


return id;
}
public String getName() {
return name;
}

public char getGender() {


return gender;
}

@Override
public String toString() {
return name + "(" + id + ")";
}

private void writeObject(ObjectOutputStream out) throws IOException {


out.defaultWriteObject();
out.writeChar('*');
}
}

public class CustomerSerialization {

public static void main(String[] args) {

List<Customer> customers = new ArrayList<>();


customers.add(new Customer(1, "Ram", 'm'));
customers.add(new Customer(2, "Shyam", 'm'));
customers.add(new Customer(3, "Sita", 'f'));
customers.add(new Customer(4, "Radha", 'f'));
customers.add(new Customer(5, "Ramkishan", 'm'));

String fileName = "yourregno.ser"; // Changed file name


serializeCustomers(customers, fileName);

int count = countCustomersWithPrefix(fileName, "Ram");


System.out.println("Number of customers whose name starts with 'Ram': " + count);
}

private static void serializeCustomers(List<Customer> customers, String fileName) {


try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName))) {
out.writeObject(customers);
System.out.println("Serialization successful. File saved as: " + fileName);
} catch (IOException e) {
System.err.println("Error during serialization: " + e.getMessage());
}
}

private static int countCustomersWithPrefix(String fileName, String prefix) {


int count = 0;
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName))) {
List<Customer> customers = (List<Customer>) in.readObject();
for (Customer customer : customers) {
if (customer.getName().startsWith(prefix)) {
count++;
}
}
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error during deserialization: " + e.getMessage());
}
return count;
}
}
OUTPUT:

Q1O. Read a Sample CSV File and Print a particular column using BufferedReader and
FileReader classes.

SOURCE CODE:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CSVReader {

public static void main(String[] args) {


// Specify the path to the CSV file
String csvFile = "sample.csv";

try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {


// Read the first line (header) to determine the column index
String headerLine = br.readLine();
if (headerLine == null) {
System.out.println("CSV file is empty");
return;
}

// Split the header line to identify the column index for the desired column
String[] headers = headerLine.split(",");
int columnIndex = -1;

// Find the index of the desired column (e.g., "Age")


for (int i = 0; i < headers.length; i++) {
if (headers[i].equalsIgnoreCase("Age")) {
columnIndex = i;
break;
}
}

// Check if the desired column exists


if (columnIndex == -1) {
System.out.println("Column 'Age' not found in the CSV file");
return;
}

// Read and print the desired column from each subsequent line
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
if (data.length > columnIndex) {
String columnValue = data[columnIndex];
System.out.println("Age: " + columnValue);
}
}

} catch (IOException e) {
System.err.println("Error reading CSV file: " + e.getMessage());
}
}
}FILE:

OUTPUT:

You might also like