• 04Mar

    One of the defining features of the Java environment is its built-in support for threads. Threads let an application perform multiple activities simultaneously. When used properly, threads let the application’s user interface remain responsive while it performs lengthy operations like network communication or very complicated computations. While user interface responsiveness is important no matter what the platform, it’s even more so on the handheld and consumer-oriented devices that the J2ME platform targets. A basic understanding of how to use threads is a key to write effective J2ME applications, whether you’re using the more limited facilities of the Connected Limited Device Configuration (CLDC) or the fuller features of the Connected Device Configuration (CDC). This article explains the concepts behind threads and how you can use them in your own applications.

    What is a Thread?

    The Java Tutorial defines a thread as “a single sequential flow of control within a program.” Threads are the fundamental units of program execution. Every running application has at least one thread. An application consisting of two or more threads is known as a multithreaded application.

    Each thread has a context associated with it. The context holds information about the thread, such as the address of the currently executing instruction and storage for local variables. The context is updated as the thread executes. The context also stores the thread’s state. A thread can be in any of the following states:

    • A running thread is executing code.
    • A ready thread is ready to execute code.
    • A suspended thread is waiting on an external event. For example, it may be waiting for data to arrive from another device. After the event occurs, the thread transitions back to the ready state.
    • A terminated thread has finished executing code.

    A thread that is running, ready, or suspended is a live thread. A terminated thread is also known as a dead thread.

    Although an application may have many threads, the underlying device has a small, fixed number of processors (often just one or two) available for code execution. Threads share these processors by taking turns being in the running state. This arrangement is called thread scheduling.

    Thread scheduling is a complicated affair over which the application has little control. The system (either the underlying operating system or the Java virtual machine, depending on how the threads are implemented) gives each ready thread a chance to run for a short time (the suspended threads are ignored), switching rapidly from one thread to another. This context switching can occur at any time. The only real influence the application has over thread scheduling is via the thread’s priority level: higher-priority threads execute more often than those with lower priority.

    Bookmark and Share

Recent Comments