Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore;
- class Filosofo implements Runnable{
- int id;
- public Filosofo(int id){
- this.id = id;
- }
- @Override
- public void run() {
- try {
- FilosofosDeadlock.Filosofar(id);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public class FilosofosDeadlock {
- public static Semaphore[] cubiertos = new Semaphore[5];
- public static void inicializar(){
- for (int i = 0; i < 5; i++){
- cubiertos[i] = new Semaphore(1);
- }
- }
- public static void Filosofar(int i) throws InterruptedException {
- int izq = i;
- int der = (i + 1) % 5;
- while(true) {
- System.out.println("El filosofo " + i + " esta pensando");
- FilosofosDeadlock.cubiertos[izq].acquire();
- FilosofosDeadlock.cubiertos[der].acquire();
- System.out.println("El filosofo " + i + " esta comiendo");
- FilosofosDeadlock.cubiertos[der].release();
- FilosofosDeadlock.cubiertos[izq].release();
- System.out.println("El filosofo " + i + " deja de comer");
- }
- }
- public static void main(String[] args){
- inicializar();
- new Thread(new Filosofo(0)).start();
- new Thread(new Filosofo(1)).start();
- new Thread(new Filosofo(2)).start();
- new Thread(new Filosofo(3)).start();
- new Thread(new Filosofo(4)).start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement