Advertisement
Guest User

Untitled

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