/*
Practical no – 4
Sandesh Kailas Tayade
Roll no - 3256
*/
// Read Write Problem
import [Link];
import [Link];
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([Link]);
[Link]("Enter message to read = ");
msg = [Link]();
}
public void run()
{
try
{
[Link]();
readcount++;
if(readcount==1)
[Link]();
[Link]();
[Link]("Thread "+[Link]().getName()+" "+[Link]);
[Link](1800);
[Link]("Thread "+[Link]().getName()+" Finished");
[Link]();
readcount--;
if(readcount==0)
[Link]();
[Link]();
}
catch (InterruptedException e)
{
[Link]();
}
}
}
static class Writer extends Thread
{
String msg;
Writer()
{
sc=new Scanner([Link]);
[Link]("Enter message to write = ");
msg=[Link]();
}
public void run()
{
/*
Practical no – 4
Sandesh Kailas Tayade
Roll no - 3256
*/
try {
[Link]();
[Link]("Thread "+[Link]().getName()+" Start writing ");
[Link]("Thread "+[Link]().getName()+" "+[Link]);
[Link](1800);
[Link]("Thread "+[Link]().getName()+" Execution Finished");
[Link]();
}
catch (InterruptedException e)
{
[Link]();
}
}
}
public static void main(String[] args)
{
Reader r1=new Reader();
[Link]("Reader1");
Reader r2=new Reader();
[Link]("Reader2");
Reader r3=new Reader();
[Link]("Reader3");
Writer wr1=new Writer();
[Link]("Writer1");
Writer wr2=new Writer();
[Link]("Writer2");
Writer wr3=new Writer();
[Link]("Writer3");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
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