Constructor and method not working as expected in Java program
I have the following code:
package principal;
public class Principal {
public static void main(String[] args) {
Thread filosofos[]=new Thread[5];
for (int i=0;i<5;i++) {
System.out.println("loop");
filosofos[i]=new Thread();
filosofos[i].start();
}
// TODO Auto-generated method stub
}
}
package principal;
public class Filosofo implements Runnable{
static final int tamanho=5;
static int talheres[]=new int[tamanho];
static Semaforo semaforo= new Semaforo(1);
static int quantidade=0;
int id;
public Filosofo(){
System.out.println("Construtor iniciado.");
for (int i=0;i<tamanho;i++) {
talheres[i]=0;
}
quantidade++;
id=quantidade;
}
public void run () {
System.out.println("Filosofo "+id+" iniciado");
try {
// Filosofo pensando
Thread.sleep(1000);
} catch (Exception e) {
}
semaforo.down();
System.out.println("Filosofo "+id+" comendo");
semaforo.up();
}
}
The program should exhibit the string “Construtor iniciado.” and the other 2 strings of method run. However when I run the code nothing happens only output that I receive is
loop
loop
loop
loop
loop
why the string of the constructor is not showing up? Why the method run is not running as expected? It looks like the constructor and the method run are not running at all, and I don’t know what is going wrong.
You have declared class Filosofo but you never create a single instance of it.
Perhaps you want to pass a new instance of Filosofo as thread constructor parameter for each thread?
Except this, instead of using a static field for counting Filosofo instances and assign them an id, why you don’t just pass the id in the constructor?
Also the other fields, don’t need to be static, pass the shared fields, like
semaforo, in the constructor and copy them in a class field.I don’t know the meaning of
talheresfield and I don’t understand why you reinitialize a static field in each instance constructor, maybe you can just initialize once in main and pass that field in the constructor of each Filosofo, as you know, arrays are not copied, only a reference to them is copied.Also instead of
catch (Exception e)you should usecatch (InterruptedException e).You should do something useful with the exception, like printing it.
If you intend to ignore an exception at least you should add a very detailed comment on why you are doing that.