cours0708/P51/compteur_solution.java

68 lines
1.2 KiB
Java

import java.io.*;
import java.util.*;
public class Compteur extends Thread {
private int n = 0;
private String nom;
// constructeur
Compteur( String nom, int n )
{
this.nom = nom;
this.n = n;
}
// methode run, code du thread
public void run()
{
for ( int i = 1 ; i <= n ; i++ ) {
try {
sleep( (int)(Math.random()*5000) );
} catch ( InterruptedException ex ) {
}
System.out.println( nom + " : " + i );
}
System.out.println( "*** " + nom + " a fini de compter jusqu'à "
+ n );
}
private static void parseArgs( String[] args )
{
if ( (args.length % 2) != 0 ) {
System.err.println( "usage : Compteurs <nom1> <n1> ..."
);
System.exit( 1 );
}
}
public static void main ( String[] args )
{
// test des arguments
parseArgs( args );
// creation de la table de compteurs
Compteur[] compteurs;
int nb_compteurs = args.length / 2;
compteurs = new Compteur[nb_compteurs];
// creation des compteurs
for ( int i = 0, j = 0 ; i < args.length ; i += 2, j++ )
compteurs[j] = new Compteur( args[i],
Integer.parseInt( args[i+1] ) );
// lancement des compteurs
for ( int i = 0 ; i < nb_compteurs ; i++ )
compteurs[i].start();
}
}