Threads of Execution in Java - dummies

By Barry Burd

Here’s a well-kept secret: Java programs are multithreaded, which means that several things are going on at once whenever you run a Java program. Sure, the computer is executing the code that you’ve written, but it’s executing other code as well (code that you didn’t write and don’t see).

All this code is being executed at the same time. While the computer executes your main method’s statements, one after another, the computer takes time out, sneaks away briefly, and executes statements from some other, unseen methods. For most simple Java programs, these other methods are ones that are defined as part of the Java Virtual Machine (JVM).

For instance, Java has an event-handling thread. While your code runs, the event-handling thread’s code runs in the background. The event-handling thread’s code listens for mouse clicks and takes appropriate action whenever a user clicks the mouse. The figure illustrates how this works.


When the user clicks the button, the event-handling thread says, “Okay, the button was clicked. So, what should I do about that?” And the answer is, “Call some actionPerformed methods.” It’s as if the event-handling thread has code that looks like this:

if (buttonJustGotClicked()) {

Of course, behind every answer is yet another question. In this situation, the follow-up question is, “Where does the event-handling thread find actionPerformed methods to call?” And there’s another question: “What if you don’t want the event-handling thread to call certain actionPerformed methods that are lurking in your code?”

Well, that’s why you call the addActionListener method. In the listing, the call


tells the event-handling thread, “Put this code’s actionPerformed method on your list of methods to be called. Call this code’s actionPerformed method whenever the button is clicked.”

So, that’s how it works. To have the computer call an actionPerformed method, you register the method with Java’s event-handling thread. You do this registration by calling addActionListener. The addActionListener method belongs to the object whose clicks (and other events) you’re waiting for.

In the listing, you’re waiting for the button object to be clicked, and the addActionListener method belongs to that button object.