Created
June 7, 2018 06:22
-
-
Save jainilvachhani/9675538d299258c0fa87a86093a0c050 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Producers | |
{ | |
int size = 3; | |
int pointer = 1; | |
public void create(int tno, Queue<Integer> buffer) throws InterruptedException | |
{ | |
Logger logger = LoggerFactory.getLogger(ProducerConsumer.class); | |
while(true) | |
{ | |
synchronized(this) | |
{ | |
if(buffer.size()!=size) | |
{ | |
buffer.add(pointer); | |
logger.info("Producer " + tno + " "+ pointer); | |
pointer++; | |
Thread.sleep(1000); | |
} | |
while(buffer.size() == size) | |
{ | |
notify(); | |
wait(); | |
} | |
} | |
} | |
} | |
} | |
class Consumers | |
{ | |
public void consume(int tno, Queue<Integer> buffer) throws InterruptedException | |
{ | |
int size = 2; | |
Logger logger = LoggerFactory.getLogger(ProducerConsumer.class); | |
while(true) | |
{ | |
synchronized(this) | |
{ | |
if(buffer.size()!=0) | |
{ | |
int value = buffer.remove(); | |
logger.info("Consumer " + tno + " " + value); | |
Thread.sleep(1000); | |
} | |
while(buffer.size()== 0) | |
{ | |
notify(); | |
wait(); | |
} | |
} | |
} | |
} | |
} | |
public class ProducerConsumer { | |
public static void main(String args[]) throws InterruptedException | |
{ | |
Queue<Integer> q = new LinkedList<>(); | |
Producers prod = new Producers(); | |
Consumers con = new Consumers(); | |
Logger logger = LoggerFactory.getLogger(ProducerConsumer.class); | |
Thread producers1 = new Thread(new Runnable() | |
{ | |
public void run() | |
{ | |
try | |
{ | |
prod.create(1,q); | |
} | |
catch(InterruptedException e) | |
{ | |
logger.error("Exception :: " , e); | |
} | |
} | |
}); | |
Thread producers2 = new Thread(new Runnable() | |
{ | |
public void run() | |
{ | |
try | |
{ | |
prod.create(2,q); | |
} | |
catch(InterruptedException e) | |
{ | |
logger.error("Exception :: " , e); | |
} | |
} | |
}); | |
Thread consumers1 = new Thread(new Runnable() | |
{ | |
public void run() | |
{ | |
try | |
{ | |
con.consume(1,q); | |
} | |
catch(InterruptedException e) | |
{ | |
logger.error("Exception :: " , e); | |
} | |
} | |
}); | |
Thread consumers2 = new Thread(new Runnable() | |
{ | |
public void run() | |
{ | |
try | |
{ | |
con.consume(2,q); | |
} | |
catch(InterruptedException e) | |
{ | |
logger.error("Exception :: " , e); | |
} | |
} | |
}); | |
producers1.start(); | |
producers2.start(); | |
consumers1.start(); | |
consumers2.start(); | |
producers1.join(); | |
producers2.join(); | |
consumers1.join(); | |
consumers2.join(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment