Vous êtes sur la page 1sur 8

Programmation multi-Thread

Java Threads

Systèmes d’exploitation- 2AINFO 1 ENIT


Threads en Java
Les Threads peuvent être créés de 2 manières:
En utilisant la classe Thread
En utilisant l’interface Runnable

Systèmes d’exploitation- 2AINFO 2 ENIT


Exemple 1: la classe Thread
public class TestThread extends Thread {
public static void main(String[] argv){
Thread th1= new TestThread();
Thread th2= new TestThread();
th1.start();
th2.start();
}

public void run( ) {


for(int i=0; i< 10;i++)
System.out.println(this.getName()+" : "+ i);
}
}

Systèmes d’exploitation- 2AINFO 3 ENIT


Cycle de vie d’un Thread
Lancer un Thread
Appeler la méthode start() , qui crée
l’environnement du thread et appelle sa méthode
run(). Elle retourne 2 threads
Arrêter, suspendre un Thread
Les méthodes stop(), suspend() et resume() sont
déconseillées : problème de internal race
condition
Attendre un Thread
Pour qu’un thread attend que tel autre thread soit
terminé: la méthode join() de la classe Thread
bloque jusqu'à ce que le thread termine. Ainsi,
Systèmes d’exploitation- 2AINFO 4 ENIT

T1.join() permet d'attendre la fin de T1


L’interface Runnable

• Comment introduire la classe Thread dans


une structure existante?
• Hériter de la classe Thread est impossible :
en Java il n’y a pas d’héritage multiple
• Solution: utiliser le mécanisme d’interface
• Interface Runnable : contient une seule
méthode run()

Systèmes d’exploitation- 2AINFO 5 ENIT


Exemple 2 : Runnable
public class RunnableClass implements Runnable{
public void run( ) {
for(int i=0; i< 10;i++)
System.out.println("Runnable:"+ i);
}
}

public class TestRunnableClass {


public static void main(String[] argv){
RunnableClass rc1 = new RunnableClass();
RunnableClass rc2 = new RunnableClass();
Thread th1= new Thread(rc1);
Thread th2= new Thread(rc2);
th1.start();
th2.start();
}
}
Systèmes d’exploitation- 2AINFO 6 ENIT
Exemple 3 :

public class ParCounting {


private static int counter = 0;

public static void main(String[] args) {

// Anonymous Runnable
Runnable task1 = new Runnable(){
@Override
public void run(){
for( ; counter<20;counter++)
System.out.println("counting : "+counter);
}
};
Systèmes d’exploitation- 2AINFO 7 ENIT
// Passing a Runnable when creating a new thread
Thread thread2 = new Thread(new Runnable() {
@Override
public void run(){
for( ; counter<20;counter++)
System.out.println("counting : "+counter);
}
});
Thread thread1 = new Thread(task1);

thread1.start();
thread2.start();
}
}
Systèmes d’exploitation- 2AINFO 8 ENIT

Vous aimerez peut-être aussi