Jump to content
Fórum Script Brasil
  • 0

Problema dos fumantes


sulense
 Share

Question

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 to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Forum Statistics

    • Total Topics
      149.6k
    • Total Posts
      646.2k
×
×
  • Create New...