Write a program for producer consumer using thread
/* Aim : Write a program for producer consumer using thread */
import java.lang.*;
class Q
{
int n;
synchronized int get()
{
System.out.println("\n\tGot : "+n);
return(n);
}
synchronized void put(int n)
{
this.n=n;
System.out.println("\n\tPut : "+n);
}
}
class producer implements Runnable
{
Q q;
producer(Q q)
{
this.q=q;
new Thread(this,"producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
}
}
}
class consumer implements Runnable
{
Q q;
consumer(Q q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
while(true)
{
q.get();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
}
}
}
class pr_7
{
public static void main(String argv[]) throws Exception
{
Q q= new Q();
new producer(q);
new consumer(q);
System.out.println("\nPress ctrl + c to stop");
}
}
/* OUTPUT
C:\jdk\bin>javac pr_7.java
C:\jdk\bin>java pr_7
Put : 0
Press ctrl + c to stop
Got : 0
Put : 1
Got : 1
Put : 2
Got : 2
Put : 3
Got : 3
Put : 4
Got : 4
Put : 5
Got : 5
C:\jdk\bin>
*/
0 comments:
Post a Comment