Threads in Java – Part I

Overview of Threads

Software applications are single / multi threaded. A traditional or heavyweight process has a single thread of control. A process with multiple threads of control can perform more tasks at a time. Modern software packages are multi threaded. Such as a browser might have one thread to display text or images while other thread retrieves update data from the network. In certain situation, a single application required to perform similar task at a same time. The benefits of using multi threads are :

  • Responsiveness : A program remain responsive even another thread is blocked or performing a larger task
  • Resource Sharing : By default threads shares data and resources of the process in which they belong
  • Economy : Threads are more economical in terms of creating process and memory allocation
  • Scalability : The benefits of multi threading can be greatly increased in a multiprocessor architecture, where threads may be running in parallel on different processors.

In this tutorial, i will focus on java threads and how to program a multi threaded software application.

Java Threads

Java Threads API provides a rich set of features for creating and managing threads. Threads are fundamental model of program execution in a java program. All java programs comprise at least a single thread that begins execution in the program’s main() method.

Creating Threads in Java

There are two possible way to create threads in a java program.

  • Create a new class that is derived from java Thread class and override its run method. The following class is derived from java Thread class and overrides its run method.
  • Define a class that implements a Runnable interface and define run method. Runnable interface is defined as follows:

    Example code for implementign Runnable interface. The following example implements Runnable interface and defines run method.