0% found this document useful (0 votes)
37 views17 pages

Exercise 6 Multithreading

Uploaded by

22i261
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)
37 views17 pages

Exercise 6 Multithreading

Uploaded by

22i261
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/ 17

Exercise 6 - Multithreading

1. Create a program that runs two threads which write two different
messages a specifiednumber of times to the same text file in append
mode. For example, thread 1 may write "hi" 10 times to the file
CompSync.txt and thread 2 may write "bye" 10 times to the same file in
append mode. Each time the thread writes the message to the file, it
sleeps 100 milliseconds to simulate the end of its time slice. Implement
this program with and without Synchronization, what difference can you
see in both.
Algorithm :

Step 1: start
Step 2: Create thread
Step 3: Store output in text file.
Step 4: Stop
Code :

import java.io.*;

class MyThread implements Runnable


{
String str;

MyThread(String str)
{
this.str = str;
}

public synchronized void run()


{
try(FileWriter fw = new FileWriter("CompSync.txt",true))
{
for(int i=0;i<10;i++)
{
try
{
fw.write(str+"\n");
Thread.sleep(100);
}
catch(InterruptedException ie) {}
}
}
catch(IOException e)
{
System.out.println("An error ocurred!");
e.printStackTrace();
}
}
}
class Ex6_Q1
{
public static void main(String args[])
{
MyThread obj1 = new MyThread("hi");
MyThread obj2 = new MyThread("bye");

Thread t1 = new Thread(obj1);


Thread t2 = new Thread(obj2);

try(FileWriter fw = new FileWriter("CompSync.txt"))


{
fw.write("This is created by Ex5_Q1.java file\n");
}
catch(IOException e)
{
System.out.println("An error ocurred : "+e.getMessage());
}

t1.start();
t2.start();
}
}
Output :
2. Without synchronization, the expected output to the file is a random
mixture of "hi" and "bye" messages depending upon the sequence in
which the two threads are scheduled to run by the scheduler (a part
of the operating system). Synchronize the code that writes to the file
using competitive synchronization such that each thread would
complete all of its writing to the file before the other thread would be
allowed to write to the file.
Accomplish this by putting the whole writing loop in a synchronized
block
Algorithm :
Step 1: Start
Step 2: Create a thread to print string in text file
Step 3: close the file
Step 4: Stop
Code :

import java.io.*;

class MyThread extends Thread


{
String str;

MyThread(String str)
{
this.str = str;
}
public void run()
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
try(FileWriter fw = new FileWriter("text1.txt",true))
{
fw.write(str+"\n");
try
{
Thread.sleep(100);
} catch(InterruptedException ie) {}
}
catch(IOException e)
{
System.out.println("An error ocurred
"+e.getMessage());
}
}
}
}
}
class Ex6_Q2
{
public static void main(String args[])
{
MyThread t1 = new MyThread("hi");
MyThread t2 = new MyThread("bye");

try(FileWriter fw = new FileWriter("text1.txt"))


{
fw.write("This is created by Ex5_Q2.java file\n");
}
catch(IOException e)
{
System.out.println("An error ocurred : "+e.getMessage());
}

t1.start();
t2.start();
}
}
Output :
3. Write a code to implement Java's multithreading features that allows
multiple customers to perform transactions on their bank accounts
concurrently while ensuring data consistency (Bank account shouldn’t
have negative balance).

Algorithm :

Step 1: Start
Step 2: Create withdraw method
Step 3: Create deposit method
Step 4: Stop
Code :

class Bank
{
private double balance;

Bank(double bal)
{
balance = bal;
}
synchronized void withDraw(String name,double amount)
{
System.out.println(name+" :");
if(balance-amount < 0)
{
System.out.println("Insufficient Balance!");
}
else
{
balance -= amount;
System.out.println("Amount withdrawn successfully!");
checkBalance();
}
}
synchronized void deposit(String name,double amount)
{
System.out.println(name+" :");
balance += amount;
System.out.println("Amount deposited successfully!");
checkBalance();
}
void checkBalance()
{
System.out.println("Available balance :"+balance);
}
}
class Transactions extends Thread
{
Bank obj;
String str, name;
double amount;

Transactions(Bank obj,String name, String str, double amount)


{
this.obj = obj;
this.name = name;
this.str = str;
this.amount = amount;
}

public void run()


{
if(str.equals("withdraw"))
{
obj.withDraw(name,amount);
}
else if(str.equals("deposit"))
{
obj.deposit(name,amount);
}
}
}
class Ex6_Q3
{
public static void main(String argsp[])
{
Bank b = new Bank(100000);

Transactions t1 = new Transactions(b,"Customer


1","deposit",1000);
Transactions t2 = new Transactions(b,"Customer
2","withdraw",1000);
Transactions t3 = new Transactions(b,"Customer
3","deposit",2000);
Transactions t4 = new Transactions(b,"Customer
4","withdraw",1500);
Transactions t5 = new Transactions(b,"Customer
5","deposit",100000);

t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Output :
4. Develop a Java application that simulates a restaurant with multiple
tables. Each table represents a potential order that a customer can
place, and you want to use multithreading to handle the orders
concurrently. You have a class called Table that represents each
table, and a class called Waiter that takes customer orders and
serves them. You should have a fixed number of tables and a
variable number of waiters. The waiters should take orders from
customers and serve them dishes. Multiple waiters should be able to
serve different tables simultaneously. Implement the concepts of
multithreading and synchronization in this scenario.
Algorithm :
Step 1 : Start
Step 2: Create thread table
Step 3: Create thread waiter
Step 4 : Run table and waiter thread
Step 5: Stop
Code :

import java.util.Scanner;
class Table extends Thread
{
String orders;
Table(String str)
{
orders = str;
}
public void run()
{
synchronized(orders)
{
System.out.println("Order placed: " + orders);
orders.notify();
}
}
}
class Waiter extends Thread {
Table obj;

Waiter(Table obj)
{
this.obj = obj;
}
public void run() {
synchronized(obj.orders) { {
try
{
obj.start();
System.out.println("Waiting for orders");
obj.orders.wait();
System.out.println("Orders taken");
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Delivered");
}
}
}

class Ex6_Q4
{
public static void main(String args[])
{
// Table class Objects
Table t1 = new Table("Juice");
Table t2 = new Table("Idli,Sambar");
Table t3 = new Table("Dosa,sambar");
Table t4 = new Table("Tea,Biscuit");

// Waiter class objects


Waiter w1 = new Waiter(t1);
Waiter w2 = new Waiter(t2);
Waiter w3= new Waiter(t3);
Waiter w4 = new Waiter(t4);
Waiter w5 = new Waiter(t1);
Waiter w6 = new Waiter(t3);
Waiter w7 = new Waiter(t4);

w1.start();
w2.start();
w3.start();
w4.start();
}
}
Output :

You might also like