Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package Semaforos;
  2.  
  3. import static es.urjc.etsii.code.concurrency.SimpleConcurrent.*;
  4. import es.urjc.etsii.code.concurrency.SimpleSemaphore;
  5.  
  6. public class Filosofos {
  7.     public static final int N_FILOSOFOS = 5;
  8.     public static final int N_TENEDORES = 5;
  9.     public static int contador = 0;
  10.     public static SimpleSemaphore[] tenedor = new SimpleSemaphore[N_TENEDORES];
  11.  
  12.     public static void filosofo(int numFilosofo) {
  13.         enterMutex();
  14.         int filosofo = contador++;
  15.         printlnI("Soy: " + filosofo);
  16.         exitMutex();
  17.        
  18.         while (true) {
  19.  
  20.             printlnI("Pensar");
  21.             sleepRandom(1000);
  22.             // Obtener tenedores
  23.            
  24.                 enterMutex("comer");
  25.                
  26.                 //Tenedor izquierda
  27.                 tenedor[filosofo].acquire();
  28.                 sleepRandom(500);
  29.                 //Tenedor derecha
  30.                 tenedor[(filosofo +1) % N_FILOSOFOS].acquire();
  31.                
  32.                 exitMutex("comer");
  33.            
  34.                 printlnI("Comer");
  35.                 sleepRandom(500);
  36.                 // Liberar tenedores
  37.                 tenedor[filosofo].release();
  38.                 tenedor[(filosofo +1) % N_FILOSOFOS].release();
  39.                 printlnI("Termine de comer");
  40.             }
  41.  
  42.         }
  43.    
  44.  
  45.     public static void main(String[] args) {
  46.         for (int i = 0; i < N_FILOSOFOS; i++) {
  47.             createThread("filosofo", i);
  48.         }
  49.         for (int i = 0; i < N_TENEDORES; i++) {
  50.             tenedor[i] = new SimpleSemaphore(1);
  51.         }
  52.         startThreadsAndWait();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement