Hi folks, Below JAVA implementation of Producer Consumer using sheared Variable.Producer Produces and Consumer Consumes.
import java.util.Random;
public class ProducerConsumer {
static int food = 0;
static boolean flag = true; // To ensure producer produces first and for toggle
static Thread producer;
static Thread consumer;
public static void main(String... args) {
// Consumer Thread
consumer = new Thread(new Runnable() {
public void run() {
synchronized (producer) { // locking producer
while (true) {
if (flag == false) {
try {
Thread.sleep(1000); // Delay so it consumes per second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am consuming: "+food);
flag = true;
producer.notify(); // notifying producer
}
}
}
}
});
consumer.start(); // Starting consumer thread
// Producer Thread
producer = new Thread(new Runnable() {
public void run() {
synchronized (consumer) { // locking consumer
while (true) {
if (flag == true) {
try {
Thread.sleep(1000); // Delay so It produces every second
} catch (InterruptedException e) {
e.printStackTrace();
}
food = new Random().nextInt(100); // producing a random number
System.out.println("I am producing: "+food);
flag = false;
consumer.notify(); // Notifying consumer
}
}
}
}
});
producer.start(); // starting Producer Thread
}
}
import java.util.Random;
public class ProducerConsumer {
static int food = 0;
static boolean flag = true; // To ensure producer produces first and for toggle
static Thread producer;
static Thread consumer;
public static void main(String... args) {
// Consumer Thread
consumer = new Thread(new Runnable() {
public void run() {
synchronized (producer) { // locking producer
while (true) {
if (flag == false) {
try {
Thread.sleep(1000); // Delay so it consumes per second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am consuming: "+food);
flag = true;
producer.notify(); // notifying producer
}
}
}
}
});
consumer.start(); // Starting consumer thread
// Producer Thread
producer = new Thread(new Runnable() {
public void run() {
synchronized (consumer) { // locking consumer
while (true) {
if (flag == true) {
try {
Thread.sleep(1000); // Delay so It produces every second
} catch (InterruptedException e) {
e.printStackTrace();
}
food = new Random().nextInt(100); // producing a random number
System.out.println("I am producing: "+food);
flag = false;
consumer.notify(); // Notifying consumer
}
}
}
}
});
producer.start(); // starting Producer Thread
}
}
No comments:
Post a Comment