Ir para conteúdo
Fórum Script Brasil
  • 0

Problema dos fumantes


sulense

Pergunta

Olá pessoal, por favor, alguém poderia me explicar esse código? obrigado!

 

 

 

 

 

CLASS AGENTE

public class Agente extends Thread {

private Mesa m; private int item1, item2;

public Agente(Mesa m) { this.m = m; }

public void run() {

while (true) {

escolherItem();

while (m.calocarItensNaMesa(item1 + item2) == false);

}

}

public void escolherItem() {

item1 = (int) (Math.random() * 3);

item2 = (int) (Math.random() * 3);

if (item1 == item2)

if (item2 == 2)

item2 = 0;

else

item2++;

}

}

CLASS MESA

public class Mesa {

private int fumante = 4;

private int estado[] = { 0, 0, 0 };

private final int ESPERANDO = 0;

private final int FUMANDO = 1;

public synchronized void fumar(int i) {

while (fumante != i) {

try {

wait();

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

if (fumante == i) {

estado[i - 1] = FUMANDO;

mostrarStatus();

} else {

System.out.println("ERROR");

}

}

public synchronized void finalizar(int i) {

estado[i - 1] = ESPERANDO;

fumante = 4;

notifyAll();

}

public synchronized boolean calocarItensNaMesa(int z) {

int cont = 0;

for (int x = 0; x < 3; x++)

if (estado[x] != FUMANDO)

cont++;

if (cont == 3) {

fumante = z;

notifyAll();

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

} } else {

return false;

} return true; }

public void mostrarStatus() {

for (int i1 = 0; i1 < 3; i1++) {

System.out.printf("F%d", (i1 + 1));

switch (estado[i1]) {

case ESPERANDO: {

System.out.printf("ESPERANDO ");

break;

}

case FUMANDO: {

System.out.printf("FUMANDO ");

break;

}

}

}

System.out.print("\n");

}

}

CLASS FUMANTE

public class Fumante extends Thread {

private Mesa m;

private final int fumante;

private final int delay = 1000;

public Papel(Mesa m, int fumante) {

this.m = m;

this.fumante = fumante;

}

public void run() {

while (true) {

m.fumar(fumante);

fumar();

m.finalizar(fumante);

}

}

public void fumar(){

try{

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

}catch (InterruptedException e) {

// TODO: handle exception

}

}

}

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...