Threads and Concurrent Programming
Threads may be seen as methods that execute at "the same time" as other methods. Normally, we think sequentially when writing a computer program. From this perspective, only one thing executes at a time. However, with today's multi-core processors, it is possible to literally have several things going on at the very same time while sharing the same memory. There are lots of ways that this is done in the real world, and this chapter goes over them in a way that you can apply to your own projects.
After studying this chapter, you will
- Understand the concept of a thread.
- Know how to design and write multithreaded programs.
- Be able to use the Thread class and the Runnable interface.
- Understand the life cycle of a thread.
- Know how to synchronize threads.
4.2 What Is a Thread?
14.3 From the Java Library: java.lang.Thread
14.4 Thread States and Life Cycle
14.5 Using Threads to Improve Interface Responsiveness
14.6 Case Study: Cooperating Threads
14.7 Case Study: The Game of Pong Chapter Summary
This chapter is about doing more than one thing at a time. Doing more than one thing at once is commonplace in our everyday lives. For example, let’s say your breakfast today consists of cereal, toast, and a cup of java. You have to do three things at
once to have breakfast: eat cereal, eat toast,and drink coffee.
Actually, you do these things “at the same time” by alternating among them: You take a spoonful of cereal, then a bite of toast, and then sip some coffee. Then you have another bite of toast, or another spoonful of cereal, more coffee, and so on, until
breakfast is finished. If the phone rings while you’re having breakfast, you will probably answer it—and continue to have breakfast, or at least to sip the coffee. This means you’re doing even more “at the same time.” Everyday life is full of examples
where we do more than one task at the same time.
The computer programs we have written so far have performed one task at a time. But there are plenty of applications where a program needs to do several things at once, or concurrently. For example, if you wrote an Internet chat program, it would
let several users take part in a discussion group. The program would have to read messages from several users at the same time and broadcast them to the other participants in the group. The reading and broadcasting tasks would have to take place concurrently.
In Java, concurrent programming is handled by threads, the topic of this chapter.
Source: R. Morelli and R. Walde, Trinity College
This work is licensed under a Creative Commons Attribution 4.0 License.