Java Multitasking  «Prev  Next»

Lesson 1

Multitasking in Java

This module introduces you to the concept of multitasking in Java.
Multithreading is the ability of a program or an operating system process to manage its use by more than one user at a time and to manage multiple requests by the same user without having to have multiple copies of the program running in the computer. With multitasking, you can make more than one event occur at the same time in your program. While this is of course possible in other languages, doing so in C, (a procedural programming language) is much more difficult than in Java. Java builds multitasking considerations directly into its language keywords, and Java provides classes and interfaces that make multitasking easy to implement. In addition, Java provides a platform-independent way to implement multitasking.
In this module, you will learn the basic concepts of multitasking, including:
  1. Threads
  2. A metaphor for multiple threads
  3. Problems involving multiple threads

You will learn about the Thread class, including
  1. How to create and start a thread
  2. The thread life cycle
  3. How a thread's priority determines when it runs
  4. How to implement the run() method for a thread

Modern Java

Synchronized Keyword

We will dive into keywords built into the Java language to help manage threads, the most important one being synchronized.
We will explore these topics mostly through the use of a program called TownHall. This program simulates a group of noisy citizens at a town hall meeting. Each citizen will be implemented as a separate thread of control, spouting off opinions whenever possible. Through synchronization, we will create an MC for this town hall event to ensure each citizen's comments are heard without being trampled on.
The basic example of a town hall application discussed in this module's lesson involves synchronization. Below is a quiz question to get you in the correct frame of mind.

Java Concurrency

Question on Synchronization:

Before which of the following can the synchronized keyword be placed, without causing a compilation error? [Select three choices.]
  1. class methods
  2. instance methods
  3. any block of code within a method
  4. variables
  5. a class

Answer: a, b, c
Note: class methods are the same as static methods.
Synchronization is performed to protect critical code from being accessed by multiple threads simultaneously.
When a thread enters synchronized code, the thread obtains the lock of the object or class depending on whether the code is non-static or static. So, both the class methods and the instance methods may be marked synchronized.
Any code block within a method can be synchronized by enclosing it in {}, so choice C is correct. Variables and classes cannot be synchronized. The following page discusses Automatic initialization of Java Variables.