/** * モニタを用いた相互排除を行うプログラム * $ java MonitorMutex で実行 */ import java.util.Random; /** * モニタを用いた相互排除アルゴリズムを実行するクラスの * インスタンスを生成し実行するクラス * MonitorMutualExclusion クラスのインスタンスを4つ作り実行する */ class MonitorMutex { public static void main (String[] args) { int maxConcurrentAccess = 2; // 同時に使える資源の数 int threadNum = 4; // スレッド数 /* モニタを生成する */ MonitorMutualExclusion.newMonitor (maxConcurrentAccess); /* スレッドを生成する */ Thread th[] = new Thread[threadNum]; for (int i=0; i 0) { --resourceNum; /* 残り資源数を減らす */ return; /* 資源が得られれば帰る */ } } pass (1000L); /* 資源が得られなければ待つ */ } } /** * 臨界領域終了 * 残り資源数を1増やす */ public void csEnd() { synchronized (ResourceMonitor.class) { /* この中には同時に1スレッドしか入れない */ ++resourceNum; /* 残り資源数を増やす */ } } /** * 残り資源数を返す * @return 残り資源数 */ public int numOfResource() { return resourceNum; } /** * 指定した時間待機する * @param latency 待機する時間(ミリ秒) */ void pass (long latency) { try { sleep (latency); // Thread のメソッド 指定したミリ秒の間一時停止する } catch (InterruptedException error_report) { System.out.println (error_report); System.exit (1); } } } /** * Monitorを用いた相互排除アルゴリズム実行クラス */ class MonitorMutualExclusion extends Thread { int threadID; // スレッド番号 String space; // 表示位置調整用 static int maxConcurrentAccess; // 同時に使える資源の数 static ResourceMonitor monitor; // 資源管理モニタ static Random random = new Random(); // ランダム遅延時間発生用 /** * モニタを生成する * @param mca 同時に使える資源の数 */ static void newMonitor (int mca) { maxConcurrentAccess = mca; monitor = new ResourceMonitor (maxConcurrentAccess); } /** * コンストラクタ * @param threadNum スレッド番号 */ MonitorMutualExclusion (int threadID) { /* 各フィールドに値設定 */ this.threadID = threadID; space = ""; // スレッド番号に合わせて表示位置を調整 for (int i=0; i