Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. package ejerciciosSemaforos;
  2.  
  3. import static es.urjc.etsii.code.concurrency.SimpleConcurrent.*;
  4. import es.urjc.etsii.code.concurrency.SimpleSemaphore;
  5.  
  6. public class ejer16 {
  7.  
  8.     private static final int N_HILOS = 4;
  9.  
  10.     public static int posicion = 0;
  11.     public static int contador = 0;
  12.     public static int pintadoLetra = 0;
  13.     private volatile static SimpleSemaphore barrera = new SimpleSemaphore(0);
  14.     private volatile static SimpleSemaphore barrera2 = new SimpleSemaphore(N_HILOS);
  15.  
  16.     public static void hilo() {
  17.  
  18.         enterMutex("posicion");
  19.         String letra = obtenerLetra(posicion++);
  20.         exitMutex("posicion");
  21.  
  22.         while (true) {
  23.  
  24.             barrera2.acquire();
  25.             print(letra);
  26.  
  27.             enterMutex();
  28.             pintadoLetra++;
  29.             if (pintadoLetra < N_HILOS) {
  30.                 exitMutex();
  31.                 barrera.acquire();
  32.                 enterMutex("M");
  33.                 contador++;
  34.                 if (contador == N_HILOS-1) {
  35.                     barrera2.release(N_HILOS);
  36.                     contador = 0;
  37.                 }
  38.                 exitMutex("M");
  39.  
  40.             } else {
  41.                 pintadoLetra = 0;
  42.                 exitMutex();
  43.                 println("-");
  44.                 barrera.release(N_HILOS - 1);
  45.             }
  46.         }
  47.     }
  48.  
  49.     public static String obtenerLetra(int i) {
  50.         if (i == 0) {
  51.             return "A";
  52.         } else if (i == 1) {
  53.             return "B";
  54.         } else if (i == 2) {
  55.             return "C";
  56.         } else if (i == 3) {
  57.             return "D";
  58.         }
  59.         return null;
  60.     }
  61.  
  62.     public static void main(String[] args) {
  63.         createThreads(N_HILOS, "hilo");
  64.         startThreadsAndWait();
  65.  
  66.     }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement