Realizzare il tipo di dato MiaCondizione definendo le operazioni c.myDelay() e c.myContinue() usate dai processi per sincronizzarsi su una condizione c. public class MioMonitor { /* Implements a monitor with two conditions by using two monitors with one condition each (and a semaphore) */ private MySemaphore mutex = new MySemaphore(); private MiaCondizione c1 = new MiaCondizione(mutex); private MiaCondizione c2 = new MiaCondizione(mutex); public void entryOne () throws InterruptedException { mutex.myDelay(); System.out.println(Thread.currentThread().getName() + ": I'm about to delay on c1."); c1.myDelay(); System.out.println(Thread.currentThread().getName() + ": I'm about to let continue on c2."); c2.myContinue(); mutex.myContinue(); System.out.println(Thread.currentThread().getName() + ": exiting the monitor."); } public void entryTwo() throws InterruptedException { mutex.myDelay(); System.out.println(Thread.currentThread().getName() + ": I'm about to let continue on c1."); c1.myContinue(); System.out.println(Thread.currentThread().getName() + ": I'm about to delay on c2."); c2.myDelay(); mutex.myContinue(); System.out.println(Thread.currentThread().getName() + ": exiting the monitor."); } } class MySemaphore { /* Producer-consumer semaphores */ protected int count = -1; public synchronized void myDelay () throws InterruptedException { count++; if (count > 0) wait(); } public synchronized void myContinue () throws InterruptedException { if (count >= 0) { count--; notify(); } } } class MiaCondizione extends MySemaphore { /* Implements conditions used by monitors */ private MySemaphore mutex; MiaCondizione (MySemaphore s) { mutex = s; } public void myDelay () throws InterruptedException { synchronized (this) { count++; mutex.myContinue(); wait(); } mutex.myDelay(); } } --------------C4C63783A2C91CD7C4ECA828 Content-Type: text/plain; charset=us-ascii; name="TestMonitor.java" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="TestMonitor.java" class SomeProcess extends Thread { MioMonitor M; boolean typeOfProcess; SomeProcess (String name, boolean t, MioMonitor sharedMonitor) { super(name); M = sharedMonitor; typeOfProcess = t; } public void run () { try { if (typeOfProcess) M.entryOne(); else M.entryTwo(); } catch (InterruptedException E) {} } } public class TestMonitor { public static void main(String args[]) { /* Tests MyMonitor */ MioMonitor M = new MioMonitor(); /* The shared monitor M is passed to the processes as parameter */ new SomeProcess ("pippo", true, M).start(); new SomeProcess("pluto", false, M).start(); new SomeProcess("paperino", false, M).start(); } }
![]() |
![]() |
Questo sito usa cookies, usandolo ne accettate la presenza. (CookiePolicy)
Torna al Dipartimento di Informatica ![]() |
|
![]() |
![]() |