giovedì 7 maggio 2015

Primi accenni di Thread

Vediamo un esempio di codice commentato per l'utilizzo dei Thread in JAVA:

CLASSE MAIN():

public class main {

public static void main(String[] args) {
SimpleThread st1= new SimpleThread("Esempio Thread");   //PASSO A PARAMETRO UNA STRINGA PER IL NOME DEL THREAD
st1.start();   //RICHIAMA IL METODO RUN() DEL THREAD
}


CLASSE SIMPLETHREAD:

public class SimpleThread  extends Thread{   //EXTENDS THREAD E' IL RICHIAMO ALLA CLASSE NATIVA DI JAVA PER I THREAD
public SimpleThread(String str)   //COSTRUTTORE
{super(str);}   //COSTRUTTORE -> super richama il costruttore della superClasse, così si possono modificare anche le proprietà private
public void run() {   //METODO RUN() RICHIAMATO DA ISTRUZIONE START DAL MAIN()
for(int i=0; i<10; i++)   //CICLO DA 10 STAMPE

System.out.println(i+ " " +getName());   //STAMPO IL NOME DEL THREAD
try
{
sleep((int)Math.random()*1000);   //METTO IN PAUSA IL THREAD PER 1 SECONDO
} catch (InterruptedException e){}
}
System.out.println("DONE! "+getName());   //STAMPO LA SCRITTA DONE! CON IL NOME DEL THREAD
}
}

Nessun commento:

Posta un commento