CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

47
CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert

Transcript of CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Page 1: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT

UV Threads

Module Java Expert

Page 2: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 2 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Module Java

Vue d’ensemble du langage Java Le langage Java : syntaxe et sémantique Programmation multi-tâche : les threads Accéder aux bases de données Composants réutilisables : le modèle MVC Développement Client/Serveur Présentation d’un IDE : WSAD / Forté / JBuilder Les serveurs d’applications J2EE Les Enterprise JavaBeans Ré-ingénierie d’applications Java

Page 3: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 3 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Threads Java

Un thread n’est pas un objet Un thread est un flot de contrôle Un thread est une série d’instructions à exécuter Un thread est une séquence imbriquée d’appels de

méthodes

Page 4: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 4 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Utilisation des Threads

Fenêtres Multiples Calcul en tâche de fond Animation Producteur/consommateur Serveur avec plusieurs clients (web ou autres) Recherche (base de données, web)

Page 5: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 5 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

L’Objet Thread

Un thread n’est pas un objet Un Thread est un objet et possède un cycle de vie Les Threads partagent la mémoire (processus)

void start()– Crée un nouveau thread et le rend exécutable

void run()– Le nouveau thread commence sa vie dans cette méthode

Page 6: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 6 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 7: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 7 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 8: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 8 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 9: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 9 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 10: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 10 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 11: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 11 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 12: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 12 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 13: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 13 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 14: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 14 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Diagrame de Création Thread

Thread t = new BThread();

t.start();

Continuer();

Objet A

BThread() {}

void start() { // creation thread}

void run() { FaireTravail();}

Objet BThread (extends Thread)

Page 15: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 15 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

L’Interface Runnable

L’objet thread implémente cette interface La méthode run() de l’objet Thread appelle celle de

l’objet Runnable Ceci permet à des threads de s’exécuter dans

n’importe quel objet, sans utiliser l’héritage.

Page 16: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 16 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple d’objet Runnable

//Création de l’objet pouvant être indépendant

Imprimante imprimante = new Imprimante();

//l’objet devient indépendant

Thread t = new Thread(imprimante);

t.start(); //appel de run()

/******************************************/

class Imprimante implements Runnable {

public void run() {

while (true) { //boucle infinie

System.out.println(“Imprimante Prête”);

}}}

Page 17: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 17 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple d’objet Runnable

//Création de l’objet pouvant être indépendant

Imprimante imprimante = new Imprimante();

//l’objet devient indépendant

imprimante.start(); //appel de run()

/******************************************/

class Imprimante implements Runnable {

Thread t = null;

public void start()

{ t = new Thread(this); // le thread est interne

t.start(); // le thread est lancé

}

public void run() {

while (true) { //boucle infinie

System.out.println(“Imprimante Prête”);

}}}

Page 18: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 18 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Cycle de vie d’un Thread

BloquéExécutable

Mort

stop()

start()

stop()

Actif

Bloquer sur I/OI/O disponible

JVM

sleep(500)

réveiller

suspend()

resume()

attendre

notifier

Page 19: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 19 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Blocage des Threads

Lorsque il y a une lecture depuis un flux, si l’entrée n’est pas disponible, le thread sera bloqué

Thread est suspendu (“bloqué”) jusqu’à ce que les I/O sont disponibles

Permettre aux autres threads d’être actif automatiquement Lorsque les I/O sont disponibles, thread se réveille et devient

“exécutable”

Page 20: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 20 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Ordonnancement du Thread

En général, le thread exécutable avec la plus haute priorité est activé (running)

Java est priority-preemptive– Si un thread de haute-priorité se réveille, et un thread de

basse priorité s’exécute– Alors le thread de haute priorité s’exécute immédiatement

Permet l’exécution à la demande– utilisation efficace du CPU

Page 21: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 21 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Famine d’un Thread

Si un thread de haute priorité n’est jamais bloqué. Alors tous les autres threads seront en attente de

CPU, et ne travailleront jamais. Prudence au niveau de la priorité d’un thread.

Page 22: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 22 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Priorités d’un Thread : Stratégies Générale

Threads qui ont beaucoup de travail à réaliser, devrait avoir une priorité plus faible.

Donner une priorité élever pour les tâches courtes. Donner aux threads devant faire des I/O une haute

priorité.– se réveiller, calculer immédiatement les données, attendre de

nouveau les I/O.

Page 23: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 23 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Conditions de la Course

Deux threads modifient simultanément un objet Les deux threads “courent” pour stocker leurs valeurs Au final, le dernier “gagne la course” (En fait, les deux perdent)

Page 24: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 24 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de Conditions de Course

class Compte {

int solde;

public void depot(int valeur)

{

int nouveauSolde;

nouveauSolde = solde + valeur;

solde = nouveauSolde;

return ;

}

}

Page 25: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 25 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de Conditions de Course

class Compte {

int solde;

public void depot(int valeur)

{

int nouveauSolde;

nouveauSolde = solde + valeur;

solde = nouveauSolde;

return ;

}

} Que se passe-t-il si l’Ordonnanceur change les threads ici?

Page 26: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 26 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Synchronisation de Thread

Mot clé du Langage : synchronized Apporte un lock sur un objet

– Lock exclusif pour le thread

Si le lock n’est pas disponible, le thread sera bloqué

Page 27: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 27 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple Synchronization

class Compte { private int solde; synchronized public void depot(int valeur) { int nouveauSolde; nouveauSolde = solde + valeur; solde = nouveauSolde ; } synchronized public void retirer(int valeur) { int nouveauSolde ; nouveauSolde = solde - valeur; solde = nouveauSolde ; }}

Page 28: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 28 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Synchronisation de Thread

Protège l’accès au code, pas aux données– Faire des membres de données privé

– Synchroniser les méthodes d’accès aux données

Mettre un “champs de force” autour de l’objet bloqué, afin qu’aucun autres threads ne puissent entrer

• Actuellement, on bloque uniquement l’accès aux autres threads synchronisés

Page 29: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 29 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Inter-blocage de Threads (Deadlock)

Si deux threads sont en compétition pour plus d’un lock

Exemple: transfert bancaire entre deux comptes– Thread A possède un lock sur le compte 1 et veut un lock

sur le compte 2

– Thread B possède un lock sur le compte 2 et veut un lock sur le compte 1

Page 30: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 30 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Eviter le Deadlock

Pas de solutions universelles Ordonné l’ acquisition d’un lock Timeout Minimiser ou supprimer la synchronisation

Page 31: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 31 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Wait et Notify

Permettre à deux threads de coopérer Basé sur un objet lock simple partagé

Page 32: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 32 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Wait et Notify: Code

consommateur:synchronized (lock) {

while (!resourceAvailable()) {

lock.wait();

}

consumeResource();

}

Page 33: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 33 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Wait and Notify: Code

Producteur:produceResource();

synchronized (lock) {

lock.notifyAll();

}

Page 34: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 34 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 35: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 35 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 36: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 36 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 37: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 37 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 38: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 38 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 39: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 39 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 40: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 40 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 41: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 41 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupèrer le lock8. Retour du wait()

9. consumeResource();10. }

Page 42: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 42 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupérer le lock8. Retour du wait()

9. consumeResource();10. }

Page 43: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 43 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupérer le lock8. Retour du wait()

9. consumeResource();10. }

Page 44: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 44 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Séquence du Wait/Notify

Objet Lock

ConsommateurThread

ProducteurThread

1. synchronized(lock){

2. lock.wait();

3. produceResource()4. synchronized(lock) {5. lock.notify();6.}

7. Récupérer le lock8. Retour du wait()

9. consumeResource();10. }

Page 45: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 45 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Wait/Notify: Détails

Souvent l’objet lock est la ressource elle-même Parfois l’objet lock est le thread producteur lui-même

Page 46: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 46 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Wait/Notify: Détails

Doit Boucler sur le wait(), dans le cas où d’autres thread s’approprient la ressource...– Après que vous êtes notifiés– Avant que vous acquérez le lock et que vous récupérez la

main suite au wait()

Utiliser lock.notifyAll() si il y a plus d’un thread en attente

Page 47: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV Threads Module Java Expert.

Module UV JavaPage 47 / 47

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple Wait/Notify : Queue Bloquante

class BlockingQueue extends Queue {

public synchronized Object remove() {

while (isEmpty()) {

wait(); // really this.wait()

}

return super.remove();

}

public synchronized void add(Object o) {

super.add(o);

notifyAll(); // this.notifyAll()

}

}