Alejandro_S_Mercado

Untitled

Sep 24th, 2025
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | Source Code | 0 0
  1. public class Productor extends Thread{
  2.     private ArrayList <Integer> lista;
  3.     private int max_size;
  4.     private int num;
  5.     private Random random=new Random();
  6.    
  7.     public Productor(ArrayList <Integer> lista,int num, int max_size) {
  8.         this.lista=lista;
  9.         this.max_size=max_size;
  10.         this.num=num;
  11.     }
  12.    
  13.     public void run() {
  14.        
  15.         int tiempoInicial=400;
  16.         int tiempoFinal=800;
  17.        
  18.            
  19.         while(true) {
  20.            
  21.             try {
  22.  
  23.                 int elemento=random.nextInt(1000)+1;
  24.                 int tiempoRetardo=random.nextInt((tiempoFinal-tiempoInicial)+1)+tiempoInicial;
  25.                 Thread.sleep(tiempoRetardo);
  26.                
  27.                 synchronized(lista) {
  28.                     while(lista.size()>=max_size) {
  29.                         System.out.println("Productor "+this.num+": Lista llena. Esperando espacio...");
  30.                         lista.wait();
  31.                     }
  32.                    
  33.                     lista.add(elemento);
  34.                    
  35.                     //lista.notify(); // Notificar a un consumidor que hay un nuevo elemento disponible
  36.                    
  37.                     System.out.println("Productor "+this.num+" produjo: "+elemento);
  38.                     lista.notifyAll(); // Notificar a todos los consumidores que hay un nuevo elemento disponible
  39.                 }
  40.                
  41.             } catch (InterruptedException e) {
  42.                 e.printStackTrace();
  43.             }
  44.         }
  45.        
  46.        
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment