Les sémaphores sont des primitives existant, par exemple, en UNIX système.
L'implémentation en Javs suit directement la définition précédente, la
méthode , fera un wait pur attendre que val soit
positive, alors que la méthode
incrémentera val et
réveillera les processus en sommeil sur le wait par un
notifyAll.
Le main suivant réalise une exclusion mutuelle très simple utilisant un sémaphore.
transparent
import java.util.Random; class Sem{ int val; public Sem(int i){val=i;} synchronized void P(){ try { while(val<=0){ wait(); } val--; } catch(InterruptedException e){} } synchronized void V(){ if(++val > 0) notifyAll(); } }
class Proc extends Thread{ Sem mutex; public Proc(String n, Sem s){ super(n); mutex=s; } public void run(){ int p,sc; Random rand = new Random(); while (true){ try { // boucle principale ....
// ... p=Math.abs(rand.nextInt()%5000); sleep(p); mutex.P(); System.out.println(getName()+ " début de sc" ); sc=Math.abs(rand.nextInt()%5000); sleep(p); System.out.println(getName()+ " fin de sc"); mutex.V(); } catch (InterruptedException e) {} } } } class Main{ public static void main(String[] args) { Sem s= new Sem(1); new Proc("un",s).start(); new Proc("deux",s).start();new Proc("trois",s).start(); } }