Java Multitasking  «Prev  Next»

Lesson 3Multiple Threads
ObjectiveDescribe the difference between single and multiple threads.

Difference between single and multiple Threads in Java

When programming with multiple threads, you can create more than one thread of control. It is like a pinball game with more than one ball in play at a time. Now it's much more difficult to follow the action and hit those flipper buttons. Luckily, with multiple threads, Java does a lot of the data management for you, making sure those balls do not slip away and that you do not tilt. For example, the runtime environment must figure out when each thread of control has access to the CPU.
Here is an example with the town hall program we will develop in this module. This program will put a number of speakers into action at once. Each speaker is independent of the others and is programmed as a separate thread and each speaker has a life of his or her own and runs sequentially.

Synchronization

The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.

Town Hall Program where Speaker1 and Speaker2 speak concurrently
Town Hall Program where Speaker1 and Speaker2 speak concurrently

While traditional languages expect single threads, Java expects multiple threads. For example, Java provides a keyword, called synchronized, that makes sure competing threads do not undo what another thread has just accomplished.
We will look at that in a moment. But before we do, let us discuss how threads are created and started.

Threads running in Java Program

Consider the following program.
public class TestClass implements Runnable{
 int x;
 public void run(){ x = 5; }
 public static void main(String[] args){
  TestClass tc = new TestClass();
  tc.x = 10;
  new Thread(tc).start(); // Line 1
  System.out.println(tc.x);
 }
}

What will it print when run? Select 1 option:
  1. 5
  2. 10
  3. It will not compile
  4. Exception at Runtime
  5. The output cannot be determined


Answer: e
Explanation:
Note that when you create and start a new Thread (at line 1) there are two threads running.
The 1) main() thread and 2) the thread that you just started. Both the threads are trying to use the same variable. Now, which thread will run first cannot be determined so whether
  1. the main() thread reads 'x' first or
  2. the new thread changes 'x' first is not known.
Therefore the output of the program cannot be determined.