构造函数和方法在Java程序中未按预期工作
构造函数和方法在Java程序中未按预期工作 我有以下代码:构造函数和方法在Java程序中未按预期工作,java,multithreading,Java,Multithreading,构造函数和方法在Java程序中未按预期工作 我有以下代码: 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 Threa
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();
}
}
为什么构造函数的字符串没有出现?为什么方法运行未按预期运行?看起来构造函数和方法run根本没有运行,我不知道出了什么问题。您从未实例化过任何Filosofo,只是线程。您从未实例化过任何Filosofo,只是线程。您声明了类Filosofo,但从未创建过它的单个实例 也许您想为每个线程传递一个新的Filosofo实例作为线程构造函数参数
package principal;
public class Principal
{
public static void main(String[] args)
{
Thread filosofos[]=new Thread[5];
for (int i=0;i<5;i++) {
filosofos[i]=new Thread(new Filosofo());
filosofos[i].start();
}
}
}
包负责人;
公共课校长
{
公共静态void main(字符串[]args)
{
线程filosofos[]=新线程[5];
对于(inti=0;i您已经声明了类Filosofo,但从未创建过它的单个实例
也许您想为每个线程传递一个新的Filosofo实例作为线程构造函数参数
package principal;
public class Principal
{
public static void main(String[] args)
{
Thread filosofos[]=new Thread[5];
for (int i=0;i<5;i++) {
filosofos[i]=new Thread(new Filosofo());
filosofos[i].start();
}
}
}
包负责人;
公共课校长
{
公共静态void main(字符串[]args)
{
线程filosofos[]=新线程[5];
对于(int i=0;我现在找到了解决方案,谢谢。@维克托看到了萨尔瓦托的答案,我加1表示给出了一个潜在的解决方案。我现在找到了解决方案,谢谢。@维克托看到了萨尔瓦托的答案,我加1表示给出了一个潜在的解决方案。