Java Multitasking  «Prev 

The Town Hall participants

We will start by looking at the participants in the town hall. cIn real life, each participant would be an independent actor and we can model this the same way in our town hall application by making each participant a separate thread. First, we will create a class to represent the MC called MC. The MC gets up and says hello. Then, any speakers who have something to say step up to the podium and speak.
The town hall meeting is run in such a way that everyone speaks their mind and no utterance gets lost in the rush to make a case. The MC allows statements to be heard one at a time. After everyone has said their piece and no other speakers are waiting to say something, the MC says goodnight, the good citizens leave, and the town hall closes. We have a number of actors in this play: an MC and some speakers. Since each of these participants is an individual, we can model each as an individual thread. (However, we will need to provide coordination among them; we will get to that shortly.) Here is how we can begin to define the participants:

class Speaker extends Thread {  
   int id;  
   int speech_count;  
   SynchronizedQueue my_soapbox; 
   Speaker(int new_id, int turns, SynchronizedQueue forum) {  
     id = new_id;  
     speech_count = turns;  
     my_soapbox = forum;  
   }  
 }

 
class MC extends Thread {  
  SynchronizedQueue podium; 
  MC (SynchronizedQueue new_forum) {   
    podium = new_forum;  
  }
 } 

Java Concurrency
  1. Speakers wear a name tag (an id). They also arrive with a certain number of points to make (a speech_count).
  2. They know where they are going to deliver this wisdom (on my_soapbox).
  3. The MC needs to know only where the podium is.
  4. Also referred to here is a new class, SynchronizedQueue (which we will explain momentarily).

Let us create five speakers at this town hall meeting. We will enlist the help of a famous pundit/moderator to assist with our little gathering and assign him the role of MC:

int num_speakers = 5; 
podium = new SynchronizedQueue();  
Speaker[] contenders = new Speaker[num_speakers];  
MC georgeWill = new MC(podium);  
georgeWill.start(); 
for (int i = 0; i < num_speakers; i++) {  
 contenders[i] = new Speaker(i, 10, podium);  
 contenders[i].start();  
} 

Notice that for each new thread we create, we must initiate it by calling its start() method. Until we do, it will not actually be doing anything. The Thread instance will exist in memory, but no system resources will be allocated to it to allow it to run as a separate process.