wait) , puis t1 va
afficher un retour à la ligne et réveiller t0.|
class Barrier { private int nall, nwait ; Barrier (int nall) { this.nall = nall ; nwait = 0 ; } synchronized void sync() { nwait++ ; if (nwait < nall) { try { wait() ; } catch (InterruptedException e) { System.exit(2) ; } } else { System.out.println() ; nwait = 0 ; notifyAll() ; } } } |
notify en notifyAll.|
class Barrier { private int nall, nwait ; Barrier() { nall = nwait = 0 ; } synchronized void register() { nall++ ; } synchronized void checkout() { nall-- ; if (nwait == nall && nwait != 0) { System.out.println() ; nwait = 0 ; notifyAll() ; } } synchronized void sync() { nwait++ ; if (nwait < nall) { try { wait() ; } catch (InterruptedException e) { System.exit(2) ; } } else { System.out.println() ; nwait = 0 ; notifyAll() ; } } } |
|
class All extends Thread { static Barrier rdv = new Barrier() ; char id ; All(char id) { this.id = id ; } public void run() { rdv.register() ; for (int i = 0 ; i < 10 ; i++) { System.out.print(id) ; rdv.sync() ; } rdv.checkout() ; } public static void main (String [] arg) { int n = 26 ; for (int i = 0 ; i < n ; i++) new All((char)('A' + i)).start() ; } } |
|
public void run() { rdv.register() ; try { for (int i = 0 ; i < 10 ; i++) { System.out.print(id) ; rdv.sync() ; } } catch (Throwable e) { } rdv.checkout() ; } |
Throwable étant une classe parente de toutes les
exceptions possibles.
C'est un peu excessif, on pourrait n'attraper que les exceptions non
signalées par le compilateur (classe Error ?).try B finallyC
qui spécifie que C sera exécuté que B termine normalement ou par
une exception.
|
public void run() { rdv.register() ; try { for (int i = 0 ; i < 10 ; i++) { System.out.print(id) ; rdv.sync() ; } } finally { rdv.checkout() ; } } |