Multi-Threaded Programming: Unrelated Threads Related Threads That Do Not Interact - Examples
Multi-Threaded Programming: Unrelated Threads Related Threads That Do Not Interact - Examples
1. unrelated threads
2. related threads that do not interact (i.e. no data
sharing)
- examples: MultipleThreads.java,
FastFoodService.java,
FastFoodServiceGUI.java
3. threads that share data and avoid interference
4. threads that pass data back and forth
- the famous example: the producer-consumer scenario
The Problem of Race Condition/Data Corruption
multiple threads that share a data object
- access of the shared object by one thread is
interfered by other threads
the problem at the system level: a race condition
- the timing of thread scheduling and execution
cannot be predicted
- example: TwoThreads.java
- fundamental issue: Which thread runs faster?
The Problem of Race Condition/Data Corruption
the problem at the application level: data corruption
- example: LittleBank.java
Solution: Use Synchronized Blocks/Methods
mutual exclusion property
- only one thread can access the shared data object
at one time
synchronization: access of the shared data object by other
threads are blocked until the current thread has completed its
access
blocking mechanism: acquisition and release of a lock on
the shared object (implemented by the JVM)
Synchronized Blocks and Methods
Example: LittleBankSync.java
Example: LittleBankV2.java