001 //package edu.unima.ky.parallel; 002 003 import java.io.*; 004 005 /** 006 * Semaphore. 007 * This class is safe against Thread InterruptedException. 008 * @author Akitoshi Yoshida 009 * @author Heinz Kredel. 010 */ 011 012 public class Semaphore implements Serializable { 013 private int init; 014 private int s; 015 private int del; 016 017 /** 018 * Constructs a default semaphore. 019 */ 020 public Semaphore() { 021 this(0); 022 } 023 024 /** 025 * Constructs a semaphore with the given upper limit value. 026 */ 027 public Semaphore(int i) { 028 if (i >=0) { init = i; } else { init = 0; } 029 s = init; 030 del = 0; 031 } 032 033 /** 034 * Finalizes this object. 035 */ 036 protected void finalize() throws Throwable { 037 if (init != s) { 038 int x = s - init; 039 System.out.println("Semaphore: " + x + " pending operations."); 040 } 041 super.finalize(); 042 } 043 044 /** 045 * Performs the P operation. 046 */ 047 public synchronized void P() throws InterruptedException { 048 while (s <= 0) { 049 del++; 050 try { this.wait(); 051 } finally { del--; } 052 } 053 s--; 054 } 055 056 /** 057 * Performs the time limited P operation. 058 */ 059 public synchronized boolean P(int m) throws InterruptedException { 060 if (s <= 0) { 061 del++; 062 try { this.wait(m); 063 } finally { del--; } 064 if (s <= 0) return false; 065 } 066 s--; 067 return true; 068 } 069 070 /** 071 * Performs the V operation. 072 */ 073 public synchronized void V() { 074 s++; 075 if (del > 0) { 076 this.notify(); 077 } 078 } 079 080 /** 081 * checks if Semaphore is positive. 082 */ 083 public boolean isPositive() { 084 return (s > 0); 085 } 086 087 }