Concepts of Programming Languages

(Sean Pound) #1
13.7 Java Threads 607

When there are threads with different priorities, the scheduler’s behav-
ior is controlled by those priorities. When the executing thread is blocked or
killed or the time slice for it expires, the scheduler chooses the thread from
the task-ready queue that has the highest priority. A thread with lower priority
will run only if one of higher priority is not in the task-ready queue when the
opportunity arises.

13.7.3 Semaphores


The java.util.concurrent.Semaphore package defines the Sema-
phore class. Objects of this class implement counting semaphores. A count-
ing semaphore has a counter, but no queue for storing thread descriptors. The
Semaphore class defines two methods, acquire and release, which cor-
respond to the wait and release operations described in Section 13.3.
The basic constructor for Semaphore takes one integer parameter, which
initializes the semaphore’s counter. For example, the following could be used to
initialize the fullspots and emptyspots semaphores for the buffer example
of Section 13.3.2:

fullspots = new Semaphore(0);
emptyspots = new Semaphore(BUFLEN);

The deposit operation of the producer method would appear as follows:

emptyspots.acquire();
deposit(value);
fullspots.release();

Likewise, the fetch operation of the consumer method would appear as follows:

fullspots.acquire();
fetch(value);
emptyspots.release();

The deposit and fetch methods could use the approach used in Section 13.7.4
to provide the competition synchronization required for the accesses to the buffer.

13.7.4 Competition Synchronization


Java methods (but not constructors) can be specified to be synchronized. A
synchronized method called through a specific object must complete its execu-
tion before any other synchronized method can run on that object. Competition
synchronization on an object is implemented by specifying that the methods
that access shared data are synchronized. The synchronized mechanism is
implemented as follows: Every Java object has a lock. Synchronized methods
must acquire the lock of the object before they are allowed to execute, which
Free download pdf