Advertisement
Guest User

Untitled

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