0% found this document useful (0 votes)
24 views4 pages

Program No 13 Java

Uploaded by

dreamsapnapbozo
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)
24 views4 pages

Program No 13 Java

Uploaded by

dreamsapnapbozo
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

PROGRAM NO:- 13

AIM:- Write a program to implement producer consumer problem in java using


thread.
SOURCE CODE:-
import java.util.Scanner;
public class synch {
public static void main(String[] args) {
int n;
System.out.println("Enter the production limit");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("The production limit is "+n);
Q q = new Q();
new Producer(q,n);
new Consumer(q,n);}}
class Q {
int n;
boolean signal = false;
synchronized int consume() {
while(!signal)
try {
System.out.println("Consumer thread sleeps");
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");}
System.out.println("Consumer thread awakes");
System.out.println("Consumed: " + n);
signal = false;
notify();
return n;}

NAMIT GUPTA,
IT-A,
163
synchronized void produce(int n) {
while(signal)
try {
System.out.println("Producer thread sleeps");
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");}
this.n = n;
System.out.println("Producer thread awakes");
signal = true;
System.out.println("Produced: " + n);
notify();}}
class Producer implements Runnable {
Q q;
int n;
Producer(Q q,int n) {
this.n=n;
this.q = q;
new Thread(this, "Producer").start();}
public void run() {
System.out.println("Producer thread created");
int i = 0;
while(i<n) {
q.produce(++i);}
System.out.println("Producer thread sleeps");}}
class Consumer implements Runnable {
Q q;
int n;
Consumer(Q q,int n) {
this.q = q;

NAMIT GUPTA,
IT-A,
163
this.n=n;
new Thread(this, "Consumer").start();}
public void run() {
System.out.println("Consumer thread created");
while(true) {
q.consume();}}}

NAMIT GUPTA,
IT-A,
163
OUTPUT:-

NAMIT GUPTA,
IT-A,
163

You might also like