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 2
The Java Thread Class

Lesson Topics

  • Thread Attributes
  • Using Threads

### Thread Attributes

The java.lang package contains the implementation of the Thread class. The declaration of Java’s Thread class is as follows:

public class Thread extends Object implements Runnable

The Thread class is derived from the Java Object class; thus, all of Object’s methods can be used with Thread.

#### Thread Attributes

A thread has several attributes—or characteristics—that define how it behaves within a Java application, as shown in Table 2-1.

Table 2-1: Thread attributes
Attribute | Description
--- | ---
Thread Body | Contains the thread’s logic. Implemented in the run() method.
Thread State | The state of activation. Is it running? Is it suspended? Has it been destroyed? Is it sleeping?
Thread Priority | Tells the Java scheduler when to run the thread in relation to other threads.
Daemon Thread | Provides a service for other threads.
Thread Group | All threads belong to a thread group. A Thread Group is a Java class which implements the capabilities of a group of related threads.

### Using Threads

There are two ways of implementing threads within a Java program.

  1. Derive a new class from Thread and allocate an instance of it.
  2. Derive a new class that implements Runnable and allocate an instance of it. Then create a new thread and pass the thread a reference to the instance of the Runnable class.

| If your class must subclass another class (the common example being Applet), you should derive a new class that implements Runnable, as outlined in Method 2 on the following page.

#### Method 1

Declare a class that extends the standard Java Thread class, as shown below:

    class UIThread extends Thread
    {
      public void run ()
      {
       while (1)
       {
         CheckMouse ();
         CheckKeyboard ();
         CheckSerialPort ();
       }
      }
    }

To use this thread, you must allocate an instance of UIThread and call the start() method, as shown below.

    UIThread m_threadUI = new UIThread ();
    m_threadUI.start ();

#### Method 2

Another way to use a thread is to declare a class that implements the Runnable interface. Then allocate a thread and pass the instance of this Runnable class to the Thread constructor.

    class UIProcess implements Runnable
    {
      public void run ()
      {
        while (1)
        {
          CheckMouse ();
          CheckKeyboar ();
          CheckSerialPort ();
        }
      }
    }

The following code must appear somewhere in the main program:

    UIProcess m_uiProcess = new UIProcess ();
    Thread m_thread = new Thread(m_uiProcess);
    m_thread.start ();

You will now take your second sample application and convert it into a Java Applet. Using this example, you will see how the Applet’s run() method is used.

COUNTER3.HTM

    <HTML>
    <HEAD>
    <TITLE>Counter3</TITLE>
    </HEAD>
    <BODY>
    <applet code=Counter3 width=400 height=200>
    </applet>
    </BODY>
    </HTML>

COUNTER3. JAVA

    import java.applet.*;
    import java.awt.*;

    class Counter3 extends Applet implements Runnable
    {
      Thread m_t1 = new Thread(this, “First Thread");
      Thread m_t2 = new Thread(this, “Second Thread");

      List m_list;

      public void start ()
      {
        BorderLayout layout = new BorderLayout ();
        setLayout (layout);
        m_list = new List (10);
        add("Center", m_list);

        m_tl.start ();
        m_t2.start ();
      }
      public void run ()
      {
        for (int i = 1; i <= 10; i++)
        {
          m_list.addItem(Thread.currentThread () .getName () + “: i is ” + i);
        }
        m_list.addItem(Thread.currentThread () . getName () + “ is finished”);
      }
    }

Figure 2-1 COUNTER3.JAVA in action

| The sequence of the execution of the threads seems to rotate better than the corresponding console application (which was demonstrated earlier in this course). This topic will be covered later in this course (when the Java scheduler is explained).

Lab 1: Generating Stock Information

This lab exercise will give you an introduction to programming multiple threads in Java. In this course, the subject of the stock market will be used to write a series of applications that relate to this subject.

Need to Generate Data

In order to do anything with stocks, you will need to generate some stock data (you could always obtain stock data from the Internet, but this will have to wait for later). Our first application involves generating some fabricated data for a series of stocks of our choosing.

This application will be a Java console application. There is no need for a user interface for the first task, and there is no need to make it an Applet. Therefore, it will be a simple console application.

You will pick n stocks and write information regarding each stock to a separate file. (A good value for n is 3). A stock has three characteristics:

  1. the name of the stock (for example, “MSFT”)
  2. the low price in a price range (for example, 110.25)
  3. the high price in the price range (for example, 130.875)

Define n stocks and for each stock, create an empty file called STOCK. STK. For instance, if a stock’s symbol is “MSFT,” create an empty file called MSFT.STK. For each stock, generate a series of random prices that fall within the price range and write that price out to the file. Each price should be in ASCII and appear on a separate line. Remember: stock prices are calculated in eighths of a dollar.

For example, the contents of the first few lines of MSFT.STK might appear as follows:

    121.375
    128
    127.25
    124.25
    122.875

If there are n stocks, you should create n separate threads. Each thread should be responsible for generating random prices for each stock and writing out the price information about each stock to the appropriate file. Do price generation and file writing for five seconds before exiting the application.

As an “extra credit” exercise, stop an individual thread if the corresponding stock’s price ever reaches its high price range.

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.