Home > Articles > Programming > Java

Introduction to Threads in Java

What is a thread? Why should you use a thread? Learn the answers to these questions and many others with this intro to Java threads.
This chapter is from the book

This chapter is from the book

Isn't it nice to be able to read and scroll the text of a Web page while the graphics continue to load? How about having a document in a word processor print in the background while you open another document for editing? Perhaps you've enjoyed writing a response to an email message while another incoming message with a large file attached is quietly downloaded simultaneously? Threads make all this convenient functionality possible by allowing a multi-threaded program to do more than one task at a time. This book helps you learn the skills and techniques necessary to incorporate that kind of useful functionality into your Java programs.

What Is a Thread?

When a modern operating system wants to start running a program, it creates a new process. A process is a program that is currently executing. Every process has at least one thread running within it. Sometimes threads are referred to as lightweight processes . A thread is a path of code execution through a program, and each thread has its own local variables, program counter (pointer to the current instruction being executed), and lifetime. Most modern operating systems allow more than one thread to be running concurrently within a process. When the Java Virtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be spawned (created).

  • Normally, you would think of Java code execution starting with the main method and proceeding in a path through the program until all the statements in main are completed. This is an example of a single thread. This "main" thread is spawned by the JavaVM, begins execution with the main method, executes all the statements in main, and dies when the main method completes.

  • A second thread is always running in the JavaVM: the garbage collection thread. It cleans up discarded objects and reclaims their memory. Therefore, even a simple Java program that only prints Hello World to System.out is running in a multi-threaded environment: The two threads are the main thread and the garbage collection thread.

When a Java program includes a graphical user interface (GUI), the JavaVM automatically starts even more threads. One of these threads is in charge of delivering GUI events to methods in the program; another is responsible for painting the GUI window.

For example, imagine that a GUI-based program's main thread is performing a complex and long-running calculation and that while this is going on, the user clicks a Stop Calculation button. The GUI event thread would then invoke the event handling code written for this button, allowing the calculation thread to be terminated. If only one thread was present, both of these could not be done simultaneously, and interruption would be difficult.

Why Use Multiple Threads?

In many situations, having more than one thread running in a program is beneficial. Here's a more in-depth look at why this can be good.

Better Interaction with the User

If only one thread was available, a program would be able to do only one thing at a time. In the word processor example, how nice it was to be able to open a second document while the first document was being formatted and queued to the printer. In some older word processors, when the user printed a document, he or she had to wait while the document was prepared for printing and sent to the printer. More modern word processors exploit multiple threads to do these two things at the same time. In a one-processor system, this is actually simulated by the operating system rapidly switching back and forth between two tasks, allowing for better user interaction.

From the perspective of a microprocessor, even the fastest typist takes a tremendous amount of time between keystrokes. In these large gaps of time, the processor can be utilized for other tasks. If one thread is always waiting to give a quick response to a user's actions, such as clicking the mouse or pressing a key, while other threads are off doing other work, the user will perceive better response from the system.

Simulation of Simultaneous Activities

Threads in Java appear to run concurrently, even when only one physical processor exists. The processor runs each thread for a short time and switches among the threads to simulate simultaneous execution. This makes it seem as if each thread has its own processor, creating a virtual multiple processor system. By exploiting this feature, you can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is running for only a brief time before the context is switched to the next thread.

Exploitation of Multiple Processors

In some machines, several real microprocessors are present. If the underlying operating system and the implementation of the JavaVM exploit the use of more than one processor, multi-threaded Java programs can achieve true simultaneous thread execution. A Java program would not have to be modified because it already uses threads as if they were running on different processors simultaneously. It would just be able to run even faster.

Do Other Things While Waiting for Slow I/O Operations

Input and Output (I/O) operations to and from a hard disk or especially across a network are relatively slow when compared to the speed of code execution in the processor. As a result, read/write operations may block for quite a while, waiting to complete.

  • In the java.io package, the class InputStream has a method, read(), that blocks until a byte is read from the stream or until an IOException is thrown. The thread that executes this method cannot do anything else while awaiting the arrival of another byte on the stream. If multiple threads have been created, the other threads can perform other activities while the one thread is blocked, waiting for input.
  • For example, say that you have a Java applet that collects data in various TextField components (see Figure 1.1).

FIGURE 1.1 The screen layout of the slow network transmission example.

  • Figure 1.2 shows an abstract pseudo-code model of how two threads can be used to provide better user interaction. The first thread is the GUI event thread, and it spends most of its time blocked in the waitForNextEvent() method. The second thread is the worker thread, and it is initially blocked, waiting for a signal to go to work in the waitUntilSignalled() method. After the fields are populated, the user clicks on a Transmit Data button. The GUI event thread unblocks and then enters the deliverEventToListener() method. That method invokes the actionPerformed() method, which signals the worker thread, and immediately returns to the waitForNextEvent() method. The worker thread unblocks, leaves the waitUntilSignaled() method, and enters the gatherDataAndTransmit() method. The worker thread gathers the data, transmits it, and blocks, waiting to read a confirmation message from the server. After reading the confirmation, the worker thread returns to the waitUntilSignalled() method.

FIGURE 1.2 The partitioning of the work between two threads.

By dividing the work between two threads, the GUI event-handling thread is free to handle other user-generated events. In particular, you might want another button, labeled Cancel Request, that would signal the worker thread to cancel the interaction with the server. If you had not used a worker thread to perform the interaction with the server, but simply had the GUI event thread do the work, the interruption activity triggered by the Cancel Request button would not be possible.

Simplify Object Modeling

Object-oriented analysis of a system before it is built can lead to a design requiring some of the objects to have a thread running within them. This kind of object can be thought of as active, as opposed to passive. A passive object changes its internal state only when one of its methods is invoked. An active object may change its internal state autonomously.

  • As an example, consider building a digital clock graphical component that displays the current system time in hours and minutes. Every 60 seconds, the minutes (and possibly the hours) displayed on this component will have to change. The simplest design is to have a thread running inside the clock component and dedicated to updating the digits when necessary. Otherwise, an external thread would have to continually check whether it is time to update a digit, in addition to performing its other duties. What if that external thread had to read data from an InputStream, and it was blocked, waiting for a byte for longer than a minute? Here, exploiting the benefits of multi-threaded programming simplifies the solution.

When Multiple Threads Might Not Be Good

It's not always a good idea to add more threads to the design of a program. Threads are not free; they carry some resource overhead.

  • Each Thread object that is instantiated uses memory resources. In addition to the memory used by the object itself, each thread has two execution call stacks allocated for it by the JavaVM. One stack is used to keep track of Java method calls and local variables. The other stack is used to keep track of native code (typically, C code) calls.

Each thread also requires processor resources. Overhead is inherent in the scheduling of threads by the operating system. When one thread's execution is suspended and swapped off the processor, and another thread is swapped onto the processor and its execution is resumed, this is called a context switch . CPU cycles are required to do the work of context switching and can become significant if numerous threads are running.

  • There is also work involved in starting, stopping, and destroying a Thread object. This cost must be considered when threads are used for brief background tasks. For example, consider the design of an email program that checks for new mail every 5 minutes. Rather than create a new thread to check for mail each time, it would be more efficient to have the same thread keep running and sleep for 5 minutes between each query.

When adding additional threads to the design of a system, these costs should be considered.

Java's Built-in Thread Support

  • One of the great things about Java is that it has built-in support for writing multi-threaded programs. Java's designers knew the value of multi-threaded programming and wisely decided to include support for threads directly in the core of Java. Chapter 7, "Controlling Concurrent Access to an Object," explores how in the Java language, the synchronized keyword is used to lock objects and classes to control concurrent access to data. The classes Thread and ThreadGroup are right in the core API in the java.lang package. The superclass of all classes in Java, Object, has inter-thread communication support built in through the wait() and notify() methods (see Chapter 8, "Inter-Thread Communication"). Even if an underlying operating system does not support the concept of threads, a well-written JavaVM could simulate a multi-threaded environment. In Java, thread support was not an afterthought, but included by design from the beginning.

Easy to Start, Tough to Master

It's relatively easy to get started with multi-threaded programming in Java. By building automatic garbage collection into Java, the error-prone work of knowing exactly when the memory for an object can be freed is simplified for developers. Similarly, because threads are an integral part of Java, tasks such as acquiring and releasing a lock on an object are simplified (especially releasing a lock when an unanticipated runtime exception occurs).

Although a Java developer can incorporate multiple threads into his or her program with relative ease, mastering the use of multiple threads and communication among them takes time and knowledge. This book introduces the basics of multi-threaded programming and then moves on to more advanced topics and techniques to help your mastery of Java threads.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020