Andry
Andry

Reputation: 181

Multithreading programming in Java, using semaphores

I'm Learning Java multithreading and I have problem, I can't understand Semaphores. How can I execute threads in this order? for example : on image1 : the 5-th thread start running only then 1-st and 2-nd is finished to execute.

Image 2:

enter image description here


Image 1:

enter image description here

I upload now images for better understanding . :))

Upvotes: 4

Views: 1729

Answers (2)

yousafsajjad
yousafsajjad

Reputation: 973

Synchronized is used so that each thread will enter that method or that portion of the code on at a time. If you want to

public class CountingSemaphore {
  private int value = 0;
  private int waitCount = 0;
  private int notifyCount = 0;

  public CountingSemaphore(int initial) {
    if (initial > 0) {
      value = initial;
    }
  }

  public synchronized void waitForNotify() {
    if (value <= waitCount) {
      waitCount++;
      try {
        do {
          wait();
        } while (notifyCount == 0);
      } catch (InterruptedException e) {
        notify();
      } finally {
        waitCount--;
      }
      notifyCount--;
    }
    value--;
  }

  public synchronized void notifyToWakeup() {
    value++;
    if (waitCount > notifyCount) {
      notifyCount++;
      notify();
    }
  }
}

This is an implementation of a counting semaphore. It maintains counter variables ‘value’, ‘waitCount’ and ‘notifyCount’. This makes the thread to wait if value is lesser than waitCount and notifyCount is empty.

You can use Java Counting Semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource. For example, here is a class that uses a semaphore to control access to a pool of items:

 class Pool {
   private static final MAX_AVAILABLE = 100;
   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

   public Object getItem() throws InterruptedException {
     available.acquire();
     return getNextAvailableItem();
   }

   public void putItem(Object x) {
     if (markAsUnused(x))
       available.release();
   }

   // Not a particularly efficient data structure; just for demo

   protected Object[] items = ... whatever kinds of items being managed
   protected boolean[] used = new boolean[MAX_AVAILABLE];

   protected synchronized Object getNextAvailableItem() {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (!used[i]) {
          used[i] = true;
          return items[i];
       }
     }
     return null; // not reached
   }

   protected synchronized boolean markAsUnused(Object item) {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (item == items[i]) {
          if (used[i]) {
            used[i] = false;
            return true;
          } else
            return false;
       }
     }
     return false;
   }

 }

Before obtaining an item each thread must acquire a permit from the semaphore, guaranteeing that an item is available for use. When the thread has finished with the item it is returned back to the pool and a permit is returned to the semaphore, allowing another thread to acquire that item. Note that no synchronization lock is held when acquire() is called as that would prevent an item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool, separately from any synchronization needed to maintain the consistency of the pool itself.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

Upvotes: 0

AlexWien
AlexWien

Reputation: 28727

Usually in java you use mutexes (also called monitors), which prohibits that two or more threads access the code region proctected by that mutex

That code region is defined using the sychronized statement

sychronized(mutex) {
 // mutual exclusive code begin
 // ...
 // ...
 // mutual exclusive code end

}

where mutex is defined as e.g:

Object mutex = new Object();

To prevent a task from beeing started you need advanced technics, such as barriers, defined in java.util.concurrency package.

But first make yourself confortable with the synchronized statement.

If you think that you will often use multi threading in java, you might want to read

"Java Concurrency in Practise"

Upvotes: 1

Related Questions