Lesson 6 | A town hall meeting |
Objective | Create a Thread subclass. |
Describe how the Town Hall application implements its threads.
While simple examples can help you see the bones of the idea, we will look at a more involved example by checking out what occurs in a town hall meeting.
Surely there are town hall meetings in your own town, no matter how big or small. There are always issues to discuss. If you've never been to one, you're about to experience such a meeting in all its glory. Required reading for this course.
Over the next few pages, we will look at various elements of this town hall program, including:
- The participants in this town hall meeting
- How everyone gets heard without trampling on each other's speech
You will find that this town hall application illustrates a number of tasks, including how to create threads, how to coordinate between threads, and how to wait for events to occur.
Java Concurrency
Multithreading and Concurrency
You can compare separate tasks with multiple threads (multithreading), which you execute concurrently (at the same time). Can you imagine watching a movie with your friends, pausing it so that you can (only) laugh, followed by (only) arguing? Similarly, apart from executing multiple applications concurrently, multithreading facilitates optimal use of a computers processing capabilities. Modeled around human behavior, multithreading enables the modeling of human behavior.
Multithreading is implemented by the underlying OS by dividing and allotting processor time to the running applications using multiple algorithms (round-robin, high priority first, and preemptive). Applications can execute as single or multiple processes, which might run multiple threads. Java supports multithreading by enabling you to define and create separate threads of execution in your applications. Most Java Virtual Machine (JVM) implementations run as a single process. A process is a selfcontained execution environment complete with its own private set of basic runtime resources, including memory.
A process can create multiple threads, also known as lightweight processes. Creation of a thread requires fewer resources. Multiple threads share the resources of the process in which they are created, like memory and files. They also have their own exclusive working space, like stacks and PC registers.
Every problem has a solution, and every solution has a problem.
This statement holds true for threads. Threads were created so that they could make the best use of a processors's time. An application can create multiple threads. When threads share objects among themselves, it can result in interleaving operations (thread interference) and reading inconsistent object values (memory inconsistency). You can protect shared data by synchronizing its access. But this can lead to other issues like thread contention through deadlock, starvation, and livelock.