GL4-RT5
Systèmes Temps-Réel
Chapitre 5 :
Java Temps-Réel
Olfa Mosbahi
olfamosbahi@[Link]
Rappel sur Java
Threads Java
◼ Java supporte le Multithreading
◼ Java supporte la Synchronisation
◼ Java supporte la Communication
◼ currentThread : le thread qui est en train d'être exécuté
◼ setPriority : fixe la priorité du thread
◼ Yield : provoque une "pause" du thread en
cours et un réordonnancement.
◼ getPriority : renvoie la priorité d’un thread
◼ Sleep : mise en attente d’un thread
◼ Interrupt : interruption d’un thtead
◼ Join : attente de l'arrêt d'un thread donné
◼ Suspend : suspendre un thread
◼ Resume : reprendre un thread qui a été suspendu
◼ Ramasses miette (Garbage Collector) en Java est un thread
qui a la plus faible priorité.
3
Threads Java
◼ Créer une classe qui etend la classe Thread [a]
◼ Créer une classe qui implemente l’interface Runnable [b]
Thread Runnable Thread
MyThread MyClass
(objects are threads) (objects with run() body)
[a] [b]
4
Méthode 1 : Etendre la classe Thread
◼ Create a class by extending Thread class and override
run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
◼ Create a thread:
MyThread thr1 = new MyThread();
◼ Start Execution of threads:
[Link]();
◼ Create and Execute:
new MyThread().start();
5
Un exemple
class MyThread extends Thread {
public void run() {
[Link](" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
[Link]();
}
}
6
Méthode 2 : Threads par implementation de
l’interface Runnable
◼ Create a class that implements the interface Runnable and
override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
◼ Creating Object:
MyThread myObject = new MyThread();
◼ Creating Thread Object:
Thread thr1 = new Thread( myObject );
◼ Start Execution:
[Link]();
7
Un exemple
class MyThread implements Runnable {
public void run() {
[Link](" this thread is running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
[Link]();
}
}
En Java, il existe deux méthodes pour créer des threads. La première étend
la classe Thread et la deuxième méthode implémente l'interface Runnable.
Une classe ne peut étendre qu'une seule autre classe. De plus, d'un point
de vue conception, il est plus propre de définir des tâches, puis des threads
exécutant ces tâches. La deuxième méthode est donc celle à utiliser.
8
L'état d’un Thread
create
new
start
run
running ready
yield, interrupt
Suspend, sleep, stop
wait or join Resume, interrupt Stop, return
inactive stop
finished
9
Diagramme d'état d’un Thread
Alive
Running
new CounterThread1(max); while (…) { … }
New Thread Runnable Dead Thread
[Link]();
run() method returns
Blocked
[Link]()
[Link]()
blocking IO call
waiting on a monitor
Exemple
Un programme avec 3 Threads Java
◼ Ecrire un programme qui crée 3 threads
11
Exemple
◼ class A extends Thread
◼ {
◼ public void run()
◼ {
◼ for(int i=1;i<=5;i++)
◼ {
◼ [Link]("\t From ThreadA: i= "+i);
◼ }
◼ [Link]("Exit from A");
◼ }
◼ }
◼ class B extends Thread
◼ {
◼ public void run()
◼ {
◼ for(int j=1;j<=5;j++)
◼ {
◼ [Link]("\t From ThreadB: j= "+j);
◼ }
◼ [Link]("Exit from B");
◼ }
◼ }
12
Exemple
◼ class C extends Thread
◼ {
◼ public void run()
◼ {
◼ for(int k=1;k<=5;k++)
◼ {
◼ [Link]("\t From ThreadC: k= "+k);
◼ }
◼ [Link]("Exit from C");
◼ }
◼ }
◼ class ThreadTest
◼ {
◼ public static void main(String args[])
◼ {
◼ new A().start();
◼ new B().start();
◼ new C().start();
◼ }
◼ }
13
Run
◼ [raj@mundroo] threads [1:76] java ThreadTest
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
14
Priorité d’un Thread
◼ En Java, à chaque thread est associé une
priorité (ordre dans lequel il est prevu pour
s’executer). Les threads ont par default la
meme priorité (NORM_PRIORITY) et ils sont
servis en utilisant la politique FCFS (First come first
served).
◼ Java permet aux users de changer la priorité :
◼ [Link](intNumber)
◼ MIN_PRIORITY = 1
◼ NORM_PRIORITY=5
◼ MAX_PRIORITY=10
15
Priorité d’un Thread
1 = MIN_PRIORITY, 10 = MAX_PRIORITY
int P = [Link]();
[Link](Thread.MAX_PRIORITY);
Si un thread de priorité P est à l'état prêt, aucun
thread de priorité inférieure à P ne sera déplacé
vers l'état d'exécution.
Pour les threads de priorité égale, les ressources
CPU sont partagées, à tour de rôle (round-robin).
16
Exemple
class A extends Thread
{
public void run()
{
[Link]("Thread A started");
for(int i=1;i<=4;i++)
{
[Link]("\t From ThreadA: i= "+i);
}
[Link]("Exit from A");
}
}
class B extends Thread
{
public void run()
{
[Link]("Thread B started");
for(int j=1;j<=4;j++)
{
[Link]("\t From ThreadB: j= "+j);
}
[Link]("Exit from B");
}
}
17
Exemple
class C extends Thread
{
public void run()
{
[Link]("Thread C started");
for(int k=1;k<=4;k++)
{
[Link]("\t From ThreadC: k= "+k);
}
[Link]("Exit from C");
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
[Link](Thread.MAX_PRIORITY);
[Link]([Link]()+1);
[Link](Thread.MIN_PRIORITY);
[Link]("Started Thread A");
[Link]();
[Link]("Started Thread B");
[Link]();
[Link]("Started Thread C");
[Link]();
[Link]("End of main thread");
}
} 18
Accès aux Ressources partagées
◼ L’accès aux Resources partagées doit etre
coordonné.
◼ Imprimante (deux jobs ne peuvent pas etre
imprimés en meme temps)
◼ Des operations simultanées sur un compte bancaire.
◼ Les operations suivantes peuvent-elles etre
effectuées simultanement sur le meme compte?
◼ Deposit()
◼ Withdraw()
◼ Enquire()
19
Ressources partagées
◼ Si un thread essaye de lire des données et un
autre thread essaye de changer les memes
données, ceci emmène vers un état incohérent.
◼ Ceci peut etre évité en synchronisant l’accès
aux données.
◼ Utiliser “Synchronized” method:
◼ public synchronized void update()
◼ {
◼ …
◼ }
20
Exemple
class InternetBankingSystem {
public static void main(String [] args ) {
Account accountObject = new Account ();
Thread t1 = new Thread(new MyThread(accountObject));
Thread t2 = new Thread(new YourThread(accountObject));
Thread t3 = new Thread(new HerThread(accountObject));
[Link]();
[Link]();
[Link]();
// DO some other operation
} // end main()
}
21
Exemple : l’objet account partagé entre 3 threads
class MyThread implements Runnable {
Account account;
public MyThread (Account s) { account = s;}
public void run() {[Link]();}
} // end class MyThread
class YourThread implements Runnable { account
Account account;
public YourThread (Account s) { account = s;}
(shared
public void run() {[Link]();} object)
} // end class YourThread
class HerThread implements Runnable {
Account account;
public HerThread (Account s) { account = s; }
public void run() {[Link]();}
} // end class HerThread
22
Monitor (Accès aux objets partagés):
serialise l’opération sur un objet partagé
class Account { // the 'monitor'
int balance;
// if 'synchronized' is removed, the outcome is unpredictable
public synchronized void deposit( ) {
// METHOD BODY : balance += deposit_amount;
}
public synchronized void withdraw( ) {
// METHOD BODY: balance -= deposit_amount;
}
public synchronized void enquire( ) {
// METHOD BODY: display balance.
}
}
23
Real-Time Specification
for Java RTSJ
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