the resource at any one time. By default, waiting threads are granted a permit in an undefined
order. By setting how to true, you can ensure that waiting threads are granted a permit in
the order in which they requested access.
To acquire a permit, call the acquire( ) method, which has these two forms:
void acquire( ) throws InterruptedException
void acquire(int num) throws InterruptedException
The first form acquires one permit. The second form acquires num permits. Most often, the
first form is used. If the permit cannot be granted at the time of the call, then the invoking
thread suspends until the permit is available.
To release a permit, call release( ), which has these two forms:
void release( )
void release(int num)
The first form releases one permit. The second form releases the number of permits
specified by num.
To use a semaphore to control access to a resource, each thread that wants to use that
resource must first call acquire( ) before accessing the resource. When the thread is done with
the resource, it must call release( ). Here is an example that illustrates the use of a semaphore:
// A simple semaphore example.
import java.util.concurrent.*;
class SemDemo {
public static void main(String args[]) {
Semaphore sem = new Semaphore(1);
new IncThread(sem, "A");
new DecThread(sem, "B");
}
}
// A shared resource.
class Shared {
static int count = 0;
}
// A thread of execution that increments count.
class IncThread implements Runnable {
String name;
Semaphore sem;
IncThread(Semaphore s, String n) {
sem = s;
name = n;
new Thread(this).start();
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home