Alejandro_S_Mercado

Untitled

Sep 24th, 2025
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | Source Code | 0 0
  1. public class Consumidor extends Thread{
  2.     private ArrayList <Integer> lista;
  3.     private int num;
  4.     private Random random = new Random();
  5.      
  6.     public Consumidor(ArrayList <Integer> lista,int num) {
  7.         this.lista=lista;
  8.         this.num=num;
  9.     }
  10.    
  11.     public void run() {
  12.         int tiempoInicial=1000;
  13.         int tiempoFinal=1500;
  14.        
  15.          while (true) {
  16.              
  17.                 try {
  18.                     int tiempoRetardo = random.nextInt((tiempoFinal - tiempoInicial) + 1) + tiempoInicial;
  19.                     Thread.sleep(tiempoRetardo);
  20.  
  21.                     synchronized (lista) {
  22.                         while (lista.isEmpty()) {
  23.                             System.out.println("Consumidor (" + num + "): Lista vacía. Esperando elementos...");
  24.                             lista.wait();
  25.                         }
  26.                         int elementoConsumido = lista.remove(0);
  27.                         System.out.println("Consumidor (" + num + ") consumió: " + elementoConsumido);
  28.                     }
  29.                 } catch (InterruptedException e) {
  30.                     e.printStackTrace();
  31.                 }
  32.             }
  33.         }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment