|
|
|
|||
|
Synchronizing ThreadsSo far, this lesson has contained examples with independent, asynchronous threads. That is, each thread contained all of the data and methods required for its execution and didn't require any outside resources or methods. In addition, the threads in those examples ran at their own pace without concern over the state or activities of any other concurrently running threads.However, there are many interesting situations where separate, concurrently running threads do share data and must consider the state and activities of other threads. One such set of programming situations are known as producer/consumer scenarios where the producer generates a stream of data which then is consumed by a consumer. For example, imagine a Java application where one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. Or, as you type characters on the keyboard, the producer thread places key events in an event queue and the consumer thread reads the events from the same queue. Both of these examples use concurrent threads that share a common resource: the first shares a file, the second shares an event queue. Because the threads share a common resource, they must be synchronized in some way. The Producer/Consumer ExampleThis lesson teaches you about Java thread synchronization through a simple producer/consumer example. Locking an Object
The code segments within a program that access the same object from
separate, concurrent threads are called critical sections.
In the Java
language, a critical section can be a block or a method and are
identified with the
Using the
| |||
|