java - My Five Philosophers are all eating at the same time, why? -
this class philosopher
public class filosofo implements runnable{ public string nome = null; public static bacchetta[] bacchette = new bacchetta[5]; //this whould resource public bacchetta bacchettadx; //right resource public bacchetta bacchettasx; //left resource public static int indice = 0; public int x[] = {}; public int y[] = {}; public jbutton filosofo = new jbutton(); //button associated philos. public filosofo(string nome, int sx, int dx){ indice++; for(int = 0; i<5; i++){ bacchette[i] = new bacchetta(); } this.nome = nome; this.bacchettasx = bacchette[sx]; this.bacchettadx = bacchette[dx]; } @override public synchronized void run() { random r = new random(); int random; while(true){ random = (int) r.nextint(100); pensa(5000); random = (int) r.nextint(100); mangia(5000); } } //the method mangia means phil. eating, has both chopsticks public synchronized void mangia(int tempo){ do{ if(!bacchettasx.isoccupied){ bacchettasx.isoccupied = true; bacchettasx.setchioccupa(this.nome); } if(!bacchettadx.isoccupied){ bacchettadx.isoccupied = true; bacchettadx.setchioccupa(this.nome); } }while(bacchettasx.getchioccupa().compareto(this.nome) != 0 && bacchettadx.getchioccupa().compareto(this.nome) != 0); this.filosofo.setbackground(color.green); try { sleep(1000); } catch (interruptedexception ex) { logger.getlogger(filosofo.class.getname()).log(level.severe, null, ex); } system.out.println("\t\t\t" + this.nome + " sta mangiando"); int = 0; /*for(long = 0; i<1000000000; i++){ a++; }*/ bacchettasx.isoccupied = false; bacchettadx.isoccupied = false; bacchettasx.setchioccupa(null); bacchettadx.setchioccupa(null); system.out.println("\t\t\t\t\t\t" + this.nome + " ha finito di mangiare"); this.filosofo.setbackground(color.blue); } //the method pensa means philosopher no longer eating public void pensa(int tempo){ system.out.println(this.nome + " sta ponderando"); try { sleep(tempo); } catch (interruptedexception ex) { logger.getlogger(filosofo.class.getname()).log(level.severe, null, ex); } } }
it's supposed print out in terminal what's doing what, problem should eat 1 one or in best scenario maximum 2 philosophers. however, eat together. synchronization not doing it's supposed doing. problem?
your code block
for(int = 0; i<5; i++){ bacchette[i] = new bacchetta(); }
initializes static array each time create new philosopher, end different bachettasx , bachettadx. initialize once in static code block outside of constructor.
static { for(int = 0; i<5; i++){ bacchette[i] = new bacchetta(); } }
Comments
Post a Comment