You are on page 1of 3

/*

Practical no – 4
Sandesh Kailas Tayade
Roll no - 3256
*/
// Read Write Problem
import java.util.concurrent.Semaphore;
import java.util.Scanner;

public class RWprob {

static Semaphore mutex=new Semaphore(1);


static Semaphore wrt=new Semaphore(1);
static int readcount=0;
static Scanner sc;
static String msg;
static class Reader extends Thread
{
String msg;
Reader()
{ sc=new Scanner(System.in);
System.out.print("Enter message to read = ");
msg = sc.nextLine();
}
public void run()
{
try
{
mutex.acquire();
readcount++;
if(readcount==1)
wrt.acquire();
mutex.release();
System.out.println("Thread "+Thread.currentThread().getName()+" "+this.msg);
this.sleep(1800);
System.out.println("Thread "+Thread.currentThread().getName()+" Finished");
mutex.acquire();
readcount--;
if(readcount==0)
wrt.release();
mutex.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
static class Writer extends Thread
{
String msg;
Writer()
{
sc=new Scanner(System.in);
System.out.print("Enter message to write = ");
msg=sc.nextLine();

}
public void run()
{
/*
Practical no – 4
Sandesh Kailas Tayade
Roll no - 3256
*/
try {
wrt.acquire();
System.out.println("Thread "+Thread.currentThread().getName()+" Start writing ");
System.out.println("Thread "+Thread.currentThread().getName()+" "+this.msg);
this.sleep(1800);
System.out.println("Thread "+Thread.currentThread().getName()+" Execution Finished");
wrt.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
Reader r1=new Reader();
r1.setName("Reader1");
Reader r2=new Reader();
r2.setName("Reader2");
Reader r3=new Reader();
r3.setName("Reader3");
Writer wr1=new Writer();
wr1.setName("Writer1");
Writer wr2=new Writer();
wr2.setName("Writer2");
Writer wr3=new Writer();
wr3.setName("Writer3");

r1.start();
r2.start();
r3.start();
wr1.start();
wr2.start();
wr3.start();
}
}

Output:-

Enter message to read = Hello


Enter message to read = Good Morning
Enter message to read = Have a Nice Day!!
Enter message to write = Nothing is Impossible.
Enter message to write = I am Great. I do great things.
Enter message to write = Practice makes man Perfect
Thread Reader1 Hello
Thread Reader2 Good Morning
Thread Reader3 Have a Nice Day!!
Thread Reader2 Finished
Thread Reader1 Finished
Thread Reader3 Finished
Thread Writer3 Start writing
Thread Writer3 Practice makes man Perfect.
Thread Writer3 Execution Finished
/*
Practical no – 4
Sandesh Kailas Tayade
Roll no - 3256
*/
Thread Writer1 Start writing
Thread Writer1 Nothing is Impossible.
Thread Writer1 Execution Finished
Thread Writer2 Start writing
Thread Writer2 I am Great. I do great things.
Thread Writer2 Execution Finished

You might also like