Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main
- {
- public static void main(String args[])
- {
- // creating buffer queue
- Queue q = new Queue();
- for(int i=0; i < 5; i++)
- new Consumer(q , i);
- for(int i=0; i < 4; i++)
- new Producer(q , i);
- }
- }
- public class Producer implements Runnable
- {
- Queue q;
- private int id ;
- Producer(Queue q, int id) {
- this.q = q;
- this.id=id;
- new Thread(this, "Producer").start();
- }
- public void run() {
- for(int i=0; i < 50; i++)
- // producer put items
- q.put(id ,i);
- }
- }
- public class Consumer implements Runnable
- {
- Queue q;
- private int id;
- Consumer(Queue q, int id ){
- this.q = q;
- this.id=id ;
- new Thread(this, "Consumer").start();
- }
- public void run()
- {
- for(int i=0; i < 50; i++)
- // consumer get items
- q.get(id) ;
- }
- }
- import java.util.Random;
- import java.util.concurrent.Semaphore;
- public class Queue
- {
- static Random r= new Random();
- // an item
- int item;
- String data ;
- // semCon initialized with 0 permits
- // to ensure put() executes first
- static Semaphore semCon = new Semaphore(0);
- static Semaphore semProd = new Semaphore(1);
- // to get an item from buffer
- void get(int id)
- {
- String data2 ;
- try {
- losoweOpóźnienie2();
- // Before consumer can consume an item,
- // it must acquire a permit from semCon
- semCon.acquire();
- }
- catch(InterruptedException e) {
- System.out.println("InterruptedException caught");
- }
- // consumer consuming an item
- data2="[C-" + id + "," + item + "]" ;
- System.out.println(data2 + " >> Dana= " + data);
- // After consumer consumes the item,
- // it releases semProd to notify producer
- semProd.release();
- }
- // to put an item in buffer
- void put(int id, int item)
- {
- try {
- losoweOpóźnienie1();
- // Before producer can produce an item,
- // it must acquire a permit from semProd
- semProd.acquire();
- } catch(InterruptedException e) {
- System.out.println("InterruptedException caught");
- }
- // producer producing an item
- this.item = item;
- data= "[P-" + id + "," + item + "," + r.nextInt(100) + "]";
- // After producer produces the item,
- // it releases semCon to notify consumer
- semCon.release();
- }
- private static void losoweOpóźnienie1() throws InterruptedException {
- Thread.sleep(r.nextInt(10-1));
- }
- private static void losoweOpóźnienie2() throws InterruptedException {
- Thread.sleep(r.nextInt(12-2));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement