Java Reference
In-Depth Information
Threads
In this chapter we'll investigate the facilities Java has to enable you to overlap the execution of segments
of a single program. As well as ensuring your programs run more efficiently, this capability is
particularly useful when your program must, of necessity, do a number of things at the same time: for
example, a server program on a network that needs to communicate with multiple clients.
In this chapter you will learn:
What a thread is and how you can create threads in your programs.
How to control interactions between threads.
What synchronization means and how to apply it in your code.
What deadlocks are, and how to avoid them.
How to set thread priorities.
How to get information about the threads in your programs.
Understanding Threads
Many programs, of any size, 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. Of course, if like most people your computer only has one processor,
you can't execute more than one computation at any instant, but you can 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 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 only have 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
Search WWH ::




Custom Search