16.1. Understanding Threads

Most programs of a reasonably large size will contain some code segments that are more or less independent of one another and that may execute more efficiently if the code segments could be overlapped in time. Threads provide a way to do this. If you have a machine with two or more processors, then as many computations as you have processors can be executing concurrently. Of course, if your computer has only one processor, you can't execute more than one computation at any instant, but you can still overlap input/output operations with processing.

Another reason for using threads is to allow processes in a program that need to run continuously, such as a continuously running animation, to be overlapped with other activities in the same program. Java applets in a web page are executed under the control of a single program—your browser—and threads make it possible for multiple applets to be executing concurrently. In this case the threads serve to segment the activities running under the control of the browser so that they appear to run concurrently. If you have only one processor, this is an illusion created by your operating system, since only one thread can actually be executing instructions at any given instant, but it's a very effective illusion. To produce animation, you typically put some code that draws a succession of still pictures in a loop that runs indefinitely. The code to draw the picture generally runs under the control of a timer so that ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.