Advertisement
Guest User

Filosofos Deadlock

a guest
Nov 13th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3.  
  4. class Filosofo implements Runnable{
  5. int id;
  6. public Filosofo(int id){
  7. this.id = id;
  8. }
  9.  
  10. @Override
  11. public void run() {
  12. try {
  13. FilosofosDeadlock.Filosofar(id);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19.  
  20. public class FilosofosDeadlock {
  21. public static Semaphore[] cubiertos = new Semaphore[5];
  22.  
  23. public static void inicializar(){
  24. for (int i = 0; i < 5; i++){
  25. cubiertos[i] = new Semaphore(1);
  26. }
  27. }
  28.  
  29. public static void Filosofar(int i) throws InterruptedException {
  30. int izq = i;
  31. int der = (i + 1) % 5;
  32.  
  33. while(true) {
  34. System.out.println("El filosofo " + i + " esta pensando");
  35. FilosofosDeadlock.cubiertos[izq].acquire();
  36. FilosofosDeadlock.cubiertos[der].acquire();
  37. System.out.println("El filosofo " + i + " esta comiendo");
  38. FilosofosDeadlock.cubiertos[der].release();
  39. FilosofosDeadlock.cubiertos[izq].release();
  40. System.out.println("El filosofo " + i + " deja de comer");
  41. }
  42. }
  43.  
  44. public static void main(String[] args){
  45. inicializar();
  46. new Thread(new Filosofo(0)).start();
  47. new Thread(new Filosofo(1)).start();
  48. new Thread(new Filosofo(2)).start();
  49. new Thread(new Filosofo(3)).start();
  50. new Thread(new Filosofo(4)).start();
  51.  
  52.  
  53.  
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement