Advertisement
LEANDRONIEVA

claseConsumidor

Oct 8th, 2023
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Random;
  3.  
  4. public class Consumidor extends Thread{
  5.  
  6.     ArrayList<Integer> lista;
  7.     int indice;
  8.    
  9.     public Consumidor(ArrayList<Integer> lista, int i) {
  10.         this.lista = lista;
  11.         this.indice = i;
  12.     }
  13.    
  14.     public void run() {
  15.         Random random = new Random();
  16.         int consumido;
  17.         int aux;
  18.        
  19.         aux= random.nextInt(400,800);
  20.         synchronized(lista) {
  21.             while(lista.isEmpty()){
  22.  
  23.                 System.out.println("Consumidor ("+indice+") no hay elementos");
  24.                 try {
  25.                     lista.wait();
  26.                     System.out.println("Consumidor ("+indice+")  listo para consumir");
  27.                 } catch (InterruptedException e) {
  28.                     // TODO Auto-generated catch block
  29.                     e.printStackTrace();
  30.                 }
  31.             }
  32.  
  33.             try {
  34.                 Thread.sleep(aux);
  35.                 consumido = lista.remove(0);   
  36.                 System.out.println("Consumido "+consumido+" por consumidor ("+indice+")");
  37.             } catch (InterruptedException e) {
  38.                 // TODO Auto-generated catch block
  39.                 e.printStackTrace();
  40.             }
  41.         }
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement