jac_usai

Untitled

Jun 11th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. public class Producer implements Runnable {
  2.     private final List < Integer > bufferCondiviso;
  3.     //…
  4.     public Producer(List < Integer > bufferCondiviso, int size) {
  5.         this.bufferCondiviso = bufferCondiviso;
  6.     }
  7.     @Override public void run() {
  8.         while (true) {
  9.             try {
  10.                 produce(); /* Il thread Producer prova a riempire il buffer... */
  11.             } catch (InterruptedException ex) {
  12.                 ex.printStackTrace();
  13.             }
  14.         }
  15.     }
  16.     private void produce(int i) throws InterruptedException {
  17.         /* il thread resta in stato wait se il buffer è pieno */
  18.         while (bufferCondiviso.size() == SIZE) {
  19.             synchronized(bufferCondiviso) {
  20.                 //…
  21.                 bufferCondiviso.wait();
  22.             }
  23.         }
  24.         /* il buffer non è pieno, quindi il thread può aggiungere un nuovo elemento e notificarlo al consumer */
  25.         synchronized(bufferCondiviso) {
  26.             bufferCondiviso.add(i);
  27.             bufferCondiviso.notifyAll();
  28.         }
  29.     }
  30. }
Add Comment
Please, Sign In to add comment