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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
public class MaClasse
{
/** Un objet pour bloquer/débloquer (mettre en attente) la classe mère.*/
public Object object = new Object() ;
/** Mes threads.*/
protected MonThread[] threads = null ;
public MaClasse(int nbCPU)
{
threads = new MonThread[nbCPU] ;
for (int i=0 ; i < nbCPU ; i++)
{
threads[i] = new MonThread(this) ;
threads[i].start() ;
}
}
public void ExecuterTravail()
{
while ( EncoreDuTravail )
{
if ( !ThreadLibre ) // Pas de thread libre => on attend.
synchronized ( object )
{
try {
object.wait() ;
}
catch ( InterruptedException e )
{
e.printStackTrace() ;
}
}
int free = TrouverUnThreadLibre() ; // On trouve un thread libre
DonnerConditionsAuThreadLibre(free) ; // On lui passe les instructions pour le calcul.
synchronized( threads[free].thread ) // On relance le thread pour le nouveau calcul
{
threads[free].thread.notify() ;
}
}
}
private class MonThread extends Thread
{
/** Pour bloquer/débloquer le thread.*/
public Object thread = new Object() ;
private MaClasse parent = null ;
public MonThread(MaClasse parent)
{
this.parent = parent ;
}
public void run()
{
while ( true )
{
try {
synchronized ( thread )
{
thread.wait() ; // On bloque immédiatement pour attendre les instructions.
}
}
catch(InterruptedException e)
{
e.printStackTrace() ;
}
OnFaitLeTravail() ; // Réalisation du boulot par le thread. Durée de 2 à 10 secondes.
synchronized ( parent.object ) // On relance la classe mère qui attendait un thread de libre.
{
parent.object.notify() ;
}
}
}
} |
Partager