0% found this document useful (0 votes)
22 views14 pages

Ex No: 2.1 Programs Using Threads and Multi-Threading Date:: 717822D119 - ILAKKIYAN J 24

Uploaded by

717821f256
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)
22 views14 pages

Ex No: 2.1 Programs Using Threads and Multi-Threading Date:: 717822D119 - ILAKKIYAN J 24

Uploaded by

717821f256
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/ 14

Ex no: 2.

1
Programs using threads and multi-threading
Date:

Question
Write a Java program that creates two threads T1 and T2 by extending Thread class. T1 asks
the user to enter an integer and displays a statement that indicates whether the integer is even
or odd.T2 asks the user to enter three integers and displays them in ascending and descending
order.
Aim
To develop a java program to create 2 threads to perform certain functions.

Code
import java.util.Scanner;
class T1 extends Thread {
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println("Thread T1: Enter an integer:");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println("Thread T1: The entered number is even.");
} else {
System.out.println("Thread T1: The entered number is odd.");
}
}
}
class T2 extends Thread {
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println("Thread T2: Enter three integers:");
int[] nums = new int[3];
for (int i = 0; i < 3; i++) {
nums[i] = scanner.nextInt();
}

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


for (int j = i + 1; j < 3; j++) {
if (nums[i] > nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
System.out.println("Thread T2: Ascending order:");
for (int num : nums) {

717822D119 - ILAKKIYAN J 24
System.out.print(num + " ");
}
System.out.println();
System.out.println("Thread T2: Descending order:");
for (int i = 2; i >= 0; i--) {
System.out.print(nums[i] + " ");
}
}
}
public class T1T2 {
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
t1.start();
t2.start();
}
}

Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 25
Ex no: 2.2
Programs using threads and multi-threading
Date:

Question
Write a Java program that creates 100 threads by implementing Runnable interface. Each
thread adds 1 to a variable ‘sum’ that is initially 0. Display the value of sum after each
increment.
Aim
To develop a java program to create 100 threads and increment sum.

Code
public class ThreadIncrementExample {
public static void main(String[] args) {
SumHolder sumHolder = new SumHolder();

System.out.println("Incrementing the sum :");


for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new IncrementRunnable(sumHolder));
thread.start();
}
}
}

class SumHolder {
private int sum;

public synchronized void increment() {


sum++;
System.out.print(" " + sum);
if(sum%10==0) {
System.out.println(" ");
}
}
}

class IncrementRunnable implements Runnable {


private SumHolder sumHolder;

public IncrementRunnable(SumHolder sumHolder) {


this.sumHolder = sumHolder;
}

@Override
public void run() {
sumHolder.increment();
}
}

717822D119 - ILAKKIYAN J 26
Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 27
Ex no: 2.3
Programs using threads and multi-threading
Date:

Question
Write a Java program that creates three threads to count the words in three files address.txt,
Homework.java and report.txt. and displays them in the following format:
address.txt: 1052
Homework.java: 445
report.txt: 2099

Aim
To develop a java program that create threads to get the word count from 3 different txt files.

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

public class WordCountThreads {


public static void main(String[] args) {
WordCountThread thread1 = new WordCountThread("address.txt");
WordCountThread thread2 = new WordCountThread("HomeWork.txt");
WordCountThread thread3 = new WordCountThread("report.txt");

thread1.start();
thread2.start();
thread3.start();

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

class WordCountThread extends Thread {


private String filename;

public WordCountThread(String filename) {


this.filename = filename;
}

717822D119 - ILAKKIYAN J 28
@Override
public void run() {
int wordCount = countWords(filename);
System.out.println(filename + ": " + wordCount);
}

private int countWords(String filename) {


int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
count += words.length;
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + filename);
e.printStackTrace();
}
return count;
}
}

Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 29
Ex no: 2.4
Programs using threads and multi-threading
Date:

Question
Write a Java program in which multiple threads add and remove elements from a LinkedList.
Aim
To develop a java program that creates multiple threads to add or remove elements from
linkedlist.

Code
import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();

Thread producer1 = new Thread(new Producer(list, 1));


Thread producer2 = new Thread(new Producer(list, 2));

Thread consumer1 = new Thread(new Consumer(list, 1));


Thread consumer2 = new Thread(new Consumer(list, 2));

producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
}
}

class Producer implements Runnable {


private final LinkedList<Integer> list;
private final int id;

public Producer(LinkedList<Integer> list, int id) {


this.list = list;
this.id = id;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
synchronized (list) {
list.add(i);
System.out.println("Producer " + id + " added: " + i);
list.notifyAll();
}

717822D119 - ILAKKIYAN J 30
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Consumer implements Runnable {


private final LinkedList<Integer> list;
private final int id;

public Consumer(LinkedList<Integer> list, int id) {


this.list = list;
this.id = id;
}

@Override
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (list) {
while (list.isEmpty()) {
try {
list.wait(); // Wait for the producer to add elements
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int value = list.removeFirst();
System.out.println("Consumer " + id + " removed: " + value);
}
try {
Thread.sleep((long) (Math.random() * 1000)); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

717822D119 - ILAKKIYAN J 31
Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 32
Ex no: 2.5
Programs using threads and multi-threading
Date:

Question
Consider a banking scenario in which a customer wishes to withdraw or deposit an amount
from his/her account. Write a Java program which ensures that only one person is able to
perform withdraw or deposit on a bank account at a time. Illustrate the above scenario using
the synchronization concept in Java.
Aim
To develop java program that creates threads to withdraw or deposit in bank account.

Code
class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public synchronized void deposit(double amount) {


System.out.println("Depositing " + amount);
balance += amount;
System.out.println("Deposit complete. New balance: " + balance);
}

public synchronized void withdraw(double amount) {


if (balance >= amount) {
System.out.println("Withdrawing " + amount);
balance -= amount;
System.out.println("Withdrawal complete. New balance: " + balance);
} else {
System.out.println("Insufficient funds for withdrawal");
}
}
}

class TransactionThread extends Thread {


private BankAccount account;
private boolean isDeposit;
private double amount;

public TransactionThread(BankAccount account, boolean isDeposit, double amount) {


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

717822D119 - ILAKKIYAN J 33
@Override
public void run() {
if (isDeposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
}
}

public class BankAccountExample {


public static void main(String[] args) {
BankAccount account = new BankAccount(1000);

TransactionThread thread1 = new TransactionThread(account, true, 500);


TransactionThread thread2 = new TransactionThread(account, false, 300);
TransactionThread thread3 = new TransactionThread(account, true, 200);

thread1.start();
thread2.start();
thread3.start();
}
}

Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 34
Ex no: 2.6
Programs using threads and multi-threading
Date:

Question
Write a program for Inter Thread Communication process. Create three classes’ Consumer,
Producer and Stock.
• Stock class which contains synchronized getStock() and putStock() methods.
• Producer class invokes addStock() method.
• Consumer class invokes getStock() method
• Create a Main class that starts Producer and Consumer

Aim
To develop a java program to add and remove stocks using threads.

Code
class Stock {
private int stock = 0;
private boolean available = false;

public synchronized void putStock(int value) {


while (available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stock = value;
available = true;
System.out.println("Producer produced: " + stock);
notify();
}

717822D119 - ILAKKIYAN J 35
public synchronized int getStock() {
while (!available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = false;
System.out.println("Consumer consumed: " + stock);
notify();
return stock;
}
}

class Producer extends Thread {


private Stock stock;

public Producer(Stock stock) {


this.stock = stock;
}

public void run() {


for (int i = 1; i <= 5; i++) {
stock.putStock(i);
try {
Thread.sleep(1000); // Simulating some production time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Consumer extends Thread {


private Stock stock;

public Consumer(Stock stock) {


this.stock = stock;
}

public void run() {


for (int i = 1; i <= 5; i++) {
int value = stock.getStock();
try {
Thread.sleep(2000);

717822D119 - ILAKKIYAN J 36
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
Stock stock = new Stock();
Producer producer = new Producer(stock);
Consumer consumer = new Consumer(stock);

producer.start();
consumer.start();
}
}

Output

Result
Thus, the Java program for the given condition has been successfully developed and
the output was verified.

717822D119 - ILAKKIYAN J 37

You might also like