001 //package edu.unima.ky.parallel; 002 003 /** 004 * Semaphore. 005 * This class implements a semaphore. 006 * @author Akitoshi Yoshida 007 * @author Heinz Kredel. 008 */ 009 010 public class Sema { 011 private int init; 012 private int s; 013 private int del; 014 015 /** 016 * Constructs a default semaphore. 017 */ 018 public Sema() { 019 this(0); 020 } 021 022 /** 023 * Constructs a semaphore with the given upper limit value. 024 * @param i limit. 025 */ 026 public Sema(int i) { 027 if (i >=0) { init = i; } else { init = 0; } 028 s = init; 029 del = 0; 030 } 031 032 /** 033 * Releases the ressources of the constructed semaphore. 034 */ 035 protected void finalize() throws Throwable { 036 if (init != s) { 037 int x = s - init; 038 System.out.println("sema: " + x + " pending operations."); 039 } 040 super.finalize(); 041 } 042 043 /** 044 * Performs the P operation, which causes the current thread 045 * to wait until the semaphore is positive. 046 */ 047 public synchronized void P() { 048 while (s <= 0) { 049 del++; 050 try { 051 this.wait(); 052 } catch (InterruptedException e) {} 053 del--; 054 } 055 s--; 056 } 057 058 /** 059 * The V operation increases the value of s. 060 */ 061 public synchronized void V() { 062 s++; 063 if (del > 0) { 064 this.notify(); 065 } 066 } 067 068 /** 069 * checks if Semaphore is positive. 070 */ 071 public boolean isPositive() { 072 return (s > 0); 073 } 074 075 }