Chapter 8. Threads
Threads have been around for some time, but few programmers have actually worked with them. There is even some debate over whether the average programmer can use threads effectively. In Java, working with threads can be easy and productive (at least for the most common cases). In fact, threads provide the only reasonable way to handle certain kinds of tasks. So it’s important that you become familiar with threads early in your exploration of Java.
Threads are integral to the way Java works. For example, an
applet’s paint( ) method isn’t called
by the applet itself, but rather by another thread within the Java
runtime system. At any given time, there may be many such background
threads, performing activities in parallel with your application. In
fact, it’s easy to get half a dozen or more threads running in
an applet without even trying, simply by requesting images, updating
the screen, playing audio, and so on. But these things happen behind
the scenes; you don’t normally have to worry about them. In
this chapter, we’ll talk about writing applications that create
and use their own threads explicitly.
Introducing Threads
Conceptually, a thread is a flow of control within a program. A thread is similar to the more familiar notion of a process, except that multiple threads within the same application share much of the same state—in particular, they run in the same address space. It’s not unlike a golf course, which many golfers use at the same time. Sharing the same ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access