1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public ClassPrincipale{
// Il est préférable de déclarer la variable en volatile pour que les thread puissent y accéder correctement avec sa bonne valeur
public volatile int maVariable;
public void testVariable(){
// Initialisation du thread de vérification
ThreadVerifVariable verif = new ThreadVerifVariable();
Thread th = new Thread(verif);
// Démarrage du thread (non bloquant, la méthode RUN est appelée)
th.start();
}
}
public ThreadVerifVariable() implements Runnable {
private ClassPrincipale c;
public ThreadVerifVariable(ClassPrincipale c){
this.c = c;
}
public void run(){
int oldval = c.maVariable;
while(true){
Thread.sleep(10000);//Attente 10 sec
int curval = c.maVariable;
if(curval != oldval){
System.out.println("la variable a changé !");
// Traitements
}
oldval = curval;
}
}
} |