Exercise 6 Multithreading
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.*;
MyThread(String str)
{
this.str = str;
}
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.*;
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");
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;
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");
w1.start();
w2.start();
w3.start();
w4.start();
}
}
Output :