ciao ragazzi, ho iniziato da poco a smanettare con i threads, e ho fatto uno programmino molto semplice per imparare, solo che mi da un'errore:
Questa è la classe nella quale c'è la risorsa che due thread dovrebbero decrementare
public class Risorsa {
int numero=20;
public void decrementa(){
numero--;
System.out.print(numero);
}//decrementa
}//Risorsa
Questa è la sotto classe di Thread:
public class Decrementing extends Thread {
Risorsa r;
Thread t;
public Decrementing(Risorsa r){
this.r=r;
t=new Thread(this);
}//Decrementa
public void run() {
r.decrementa();
}//run
}//Decrementing
E questo è il main:
public class ThreadMain {
public static void main(String[] args) throws InterruptedException {
Risorsa r= new Risorsa();
Decrementing d1=new Decrementing(r);
Decrementing d2=new Decrementing(r);
for(int i=0; i<5; i++){
d1.start();
d2.start();
}
}
}//ThreadMain
Se nel main tolgo quel for tutto va bene, ma se lo lascio mi da questo errore:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at ThreadMain.main(ThreadMain.java:11)
ho provato aggiungendo i comandi wait() notify() nel medoto decrementa della classe Risorsa ma niente. Qualcuno sa dirmi dove sbaglio?
GRAZIE A TUTTI!!![]()