Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Semaforos;
- import static es.urjc.etsii.code.concurrency.SimpleConcurrent.*;
- import es.urjc.etsii.code.concurrency.SimpleSemaphore;
- public class Filosofos {
- public static final int N_FILOSOFOS = 5;
- public static final int N_TENEDORES = 5;
- public static int contador = 0;
- public static SimpleSemaphore[] tenedor = new SimpleSemaphore[N_TENEDORES];
- public static void filosofo(int numFilosofo) {
- enterMutex();
- int filosofo = contador++;
- printlnI("Soy: " + filosofo);
- exitMutex();
- while (true) {
- printlnI("Pensar");
- sleepRandom(1000);
- // Obtener tenedores
- enterMutex("comer");
- //Tenedor izquierda
- tenedor[filosofo].acquire();
- sleepRandom(500);
- //Tenedor derecha
- tenedor[(filosofo +1) % N_FILOSOFOS].acquire();
- exitMutex("comer");
- printlnI("Comer");
- sleepRandom(500);
- // Liberar tenedores
- tenedor[filosofo].release();
- tenedor[(filosofo +1) % N_FILOSOFOS].release();
- printlnI("Termine de comer");
- }
- }
- public static void main(String[] args) {
- for (int i = 0; i < N_FILOSOFOS; i++) {
- createThread("filosofo", i);
- }
- for (int i = 0; i < N_TENEDORES; i++) {
- tenedor[i] = new SimpleSemaphore(1);
- }
- startThreadsAndWait();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement