top examplets

A Simple Semaphore Class

Thread A needs to wait for thread B's OK before continuing--Perhaps thread B is producing some resource that thread A is consuming. How do you do it? Use a Semaphore.

In this example, SemaphoreDemo's constructor spawns off a thread that jams a number into a variable. It needs to wait until the constructor has finished jamming the number into the variable.


SemaphoreDemo


// SemaphoreDemo.java


class SemaphoreDemo extends Thread
  {


  public static void main (String[] args)
    {
    new SemaphoreDemo();
    }


  // The thread will shove a number into here, then the constructor will
  // display it.

  int x;


  // Start a thread, wait for it to shove a number into x, then display x.

  public SemaphoreDemo()
    {
    start();
    sem.waitForEvent();
    System.out.println (x);
    }


  public void run()
    {
    x = 12345;
    sem.postEvent();
    }


  Semaphore sem = new Semaphore();


  };

Semaphore


// A simple semaphore class.

class Semaphore
  {


  // Constructor.

  public Semaphore()
    {
    count_ = 0;
    }


  // Wait for an event.  If there are no events posted, wait for one.

  public synchronized void waitForEvent()
    {
    while (count_ == 0)
      try
        {wait();}
      catch (InterruptedException e)
        {}
    count_--;
    }


  // Post an event.  If there are any threads hung in waitForEvent(), one
  // of them will be woken up and allowed to run.

  public synchronized void postEvent()
    {
    count_++;
    notify();
    }


  // The semaphore's count.

  int count_;


  };

See also


Copyright (c) 1997, 1998 by Wayne E. Conrad, All Rights Reserved
Last Updated May 6, 1998
This page has been accidentally visited times since May 1st, 1998.
HTML DTD Validated Best Viewed With Any Browser

This page hosted by Get your own Free Home Page