All ITKnowledge Source Code Search Tips Advanced Search |

| Mastering Java Threads by Marc Adler and David Herst DDC Publishing, Inc. ISBN: 1562438425 Pub Date: 05/01/99

Search this book:

Previous | Table of Contents | Next

## Chapter 1
Introduction To Threads

Lesson Topics

  • Single Threaded Programs
  • Threads & Data Space
  • Concurrent Execution
  • Writing Threaded Java Apps

### Single Threaded Programs

Prior to delving into multithreaded application development, it is important to define the concept of threading and to review the characteristics of single-threaded applications. Most computer programs are sequential in nature. You start a task, wait for the task to finish, then start another task. This is typical of a single-threaded application.

#### Single Tasking Problems

There is a problem with single tasking, however: if a certain task is slow or blocking, it can slow or halt the entire execution of a program. Consider code that implements an input monitor for a user-interface library and blocks until the user types a character, as shown below.

    main(int argc, char **argv)

    {

      int c;

      while (1)

      {

        c = getchar();

        if (c == ESC)

          break;

        ProcessKeyboardInput (c);

        ProcessMouseInput();

      }

      exit (0);
    }

Other Examples

Another example of a single-tasking application is a spreadsheet that performs automatic recalculation. The recalculation process may suspend user interaction (with the spreadsheet file or the entire operating system) until the recalculation is complete.

How can this undesirable situation be alleviated? How can you write an application that allows for particular application events to occur while not freezing the user’s system?

#### “Simulated” Multitasking

Back in the “good old days” of programming, application developers utilized a variety of techniques to simulate multitasking in order to avoid blocking waits.

Among the techniques used to avoid blocking program waits were:

  • Event loops
  • the select() function
  • timeouts (using alarms)
  • context swapping

Writing your own multitasking system can be 1) tedious and time-consuming (making it uneconomical) and 2) nonportable to other operating systems. Solutions have traditionally been proprietary in nature.

What is necessary and practical is a method of implementing multitasking within an application that is:

  • portable
  • standardized

#### Lightweight Processes & Threads

UNIX and other operating systems have pioneered the concept of lightweight processes. Lightweight processes are more commonly called threads.

| Thread: also known as a lightweight process, this is a single sequential flow of control within an application or applet process.

Multithreaded programs typically perform different tasks simultaneously. This creates the illusion of different parts of an application executing simultaneously on different computers or processors.

### Threads & Data Space

A system that has a single task with multiple threads is different than a true multitasking system.

#### What Tasks Contain

Each task in a multitasking system contains:

  • its own data space
  • its own register set

| Process switches are slow and expensive.

#### Thread Characteristics

In a multithreaded system, each thread:

  • shares the same global data space
  • can access the same exact variable in heap memory
  • can have private data variables that are allocated on the stack

Decreased Overhead

In a multithreaded application, each thread runs within the same process space; thus, the overhead of switching between different threads is much less than the overhead of switching between different processes in a multitasking system.

One beneficial aspect of threads is that it is easy for different threads to share global data. In a true multitasking system, it is usually tedious to share data between different processes.

| A system that has a single task with multiple threads is different than a true multitasking system.

### Concurrent Execution

Each thread in an application can run concurrently. A program typically has a single thread of execution. As the program runs, you can create more threads, as needed. Each thread is typically used to carry out some type of background task.

#### An Example

For example, in the spreadsheet example used earlier, a separate thread could be created which performs recalculations in the background. Another thread could be used to wait for user input.

The following characteristics apply to threads:

  • A thread can run continuously in a loop for the entire duration of the program (for example, a thread can continually poll the mouse for movements and button clicks).
  • Alternately, a thread can contain a single set of instructions that is executed just once before the thread terminates (such as a one-time spreadsheet recalculation).

| A Java program will run until all nondaemon threads have been terminated.

### Writing Threaded Java Apps

#### Exercise 1-1: Writing your first threaded Java application

The first threaded Java application you will write is a simple counter. This app will count from 1 to 10 and then exit. This file will be a simple console application, run by the stand-alone Java interpreter. Name the file COUNTER1.JAVA, copying the code shown below.

    class Counter1

    {

      public static void main(String args[])

      {

       Counter1Thread t = new Counter1Thread();

       t.start();

       System.out.println(“main() has finished.”);
     }

    }

    class Counter1Thread extends Thread

    {

      Counter1Thread()

      {

      }

      public void run()

      {

       for (int i = 1; i <= 10; i++)

       {

          System.out.println(“i is ” + i);

        {

       System.out.println(“The thread is finished”);

      }
    }

The output from the COUNTER1.JAVA program is as follows:

    main () has finished.

    i is 1

    i is 2

    i is 3

    i is 4

    i is 5

    i is 6

    i is 7

    i is 8

    i is 9

    i is 10

    The thread is finished

#### Exercise 1-2: Writing a Java app with two threads

As a variation on the first application, the following exercise adds another thread. Each thread in the application will count from 1 to 10 and then exit. Name this app COUNTER2.JAVA.

    class Counter2

    {

      public static void main(String args[])

      {

        Counter2Thread t1 = new Counter2Thread (“First Thread”);

        Counter2Thread t2 = new Counter2Thread (“Second Thread”);

        t1.start();

        t2.start();

        System.out.println(“main() has finished.”);

      }

    }

    class Counter2Thread extends Thread

    {

       Counter2Thread(String szName)

       {

         super (szName);

       }

       public void run()

       {

         for (int i = 1; i <= 10; i++)

       {

          System.out.println(getName() + “:\ti is ” + i);

       }

       System.out.println(getName() + “ is finished”);

      }

    }

The output from this program is as follows:

    main () has finished.

    First Thread:  i is 1

    First Thread:  i is 2

    First Thread:  i is 3

    First Thread:  i is 4

    First Thread:  i is 5

    First Thread:  i is 6

    First Thread:  i is 7

    First Thread:  i is 8

    First Thread:  i is 9

    First Thread:  i is 10

    Second Thread: i is 1

    Second Thread: i is 2

    Second Thread: i is 3

    Second Thread: i is 4

    Second Thread: i is 5

    Second Thread: i is 6

    Second Thread: i is 7

    Second Thread: i is 8

    Second Thread: i is 9

    Second Thread: i is 10

    Second Thread is finished

    First Thread is finished

Starvation

This Java application illustrates one of the interesting problems with multiple threads—starvation. The subject of starvation will be discussed later in this course.

Previous | Table of Contents | Next

Copyright © DDC Publishing

Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.