TrabalhosGratuitos.com - Trabalhos, Monografias, Artigos, Exames, Resumos de livros, Dissertações
Pesquisar

Jantar Dos Filósofos

Trabalho Escolar: Jantar Dos Filósofos. Pesquise 860.000+ trabalhos acadêmicos

Por:   •  14/10/2013  •  1.397 Palavras (6 Páginas)  •  502 Visualizações

Página 1 de 6

JANTAR DOS FILÓSOFOS

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package jantarfilosofos;

/**

*

* @author Caio

*/

public class JantarFilosofos {

public static void main(String[] args) {

Mesa m = new Mesa();

Thread f0 = new Filosofos(0, m);

Thread f1 = new Filosofos(1, m);

Thread f2 = new Filosofos(2, m);

Thread f3 = new Filosofos(3, m);

Thread f4 = new Filosofos(4, m);

f0.start();

f1.start();

f2.start();

f3.start();

f4.start();

}

}

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package jantarfilosofos;

/**

*

* @author Caio

*/

public class Filosofos extends Thread {

private int cadeira;

private Mesa m;

private final int delay = 1000;

public Filosofos(int cadeira, Mesa m) {

this.cadeira = cadeira;

this.m = m;

}

public void run() {

while (true) {

pensar();

m.pegarGarfo(cadeira);

comer();

m.largarGarfos(cadeira);

m.mostraEstados();

}

}

public void pensar() {

try {

Thread.sleep((int) (delay * Math.random()));

} catch (Exception e) {

}

}

public void comer() {

try {

Thread.sleep((int) (delay * Math.random()));

} catch (Exception e) {

}

}

}

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package jantarfilosofos;

import java.util.concurrent.Semaphore;

/**

*

* @author Caio

*/

public class Mesa {

private final int n = 5;

private final int com_fome = 1; //Próximo a comer

private final int esperando = 0; //Aguardo a vez para ser o próximo a comer

private final int comendo = 2; //Comendo

private int estado[];

private Semaphore s[] = new Semaphore[] { new Semaphore(0),

new Semaphore(0), new Semaphore(0), new Semaphore(0),

new Semaphore(0) };

private Semaphore mutex;

private int left, right;

public Mesa() {

estado = new int[5];

mutex = new Semaphore(1);

}

public void pegarGarfo(int i) {

try {

mutex.acquire();

} catch (InterruptedException e) {

e.printStackTrace();

}

estado[i] = com_fome;

testar(i);

mutex.release();

try

...

Baixar como (para membros premium)  txt (4.2 Kb)  
Continuar por mais 5 páginas »
Disponível apenas no TrabalhosGratuitos.com