02 novembre 2008

java.lang.IllegalThreadStateException problema restart di un thread java

In alcuni casi è necessario dover gestire un numero di thread paralleli considerevole.
Si noti che in queste situazioni si presenta un deterioramento delle prestazioni dovuto principalmente al costo computazione di creazione e distruzione dei thread.
In questi casi è opportuno sviluppare una strategia tale da riuscire a riutilizzare i thread senza crearne altri. Il problema è che in Java, dopo aver creato un thread non è possibile riavviare la propria esecuzione mediante il metodo start().

Ecco un esempio di come creare un thread, escogitando un metodo per poterne gestire il "re"start.
public class MyThread extends Thread{ 
public Integer semaforoThread = new Integer(0);
// metodo run
public void run(){
try{
while(true){
// codice da far eseguire al thread
....

synchronized(semaforoThread){
semaforoThread.wait();
}
}
}catch(InterruptedException e){
System.out.println("Problemi con il thread : "+e.getMessage());
}
}
// metodo per far ripartire il thread
public void restart(){
synchronized (this.semaforoThread) {
this.semaforoThread.notify();
}
}
}

Questo è il codice per poter utilizzare tale thread :
MyThread thread = new MyThread();
thread.start();
....
// si intende restartare il thread
thread.restart();

Nessun commento: