Chapter 18. Programming with Threads


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Part IV:  Advanced Topics

In this chapter you will learn:

  • Why you sometimes need multiple threads in the same program

  • How to create a second thread by extending the Thread class

  • How to create a second thread by implementing the Runnable interface

  • How to put a thread to sleep for a time

  • How to control concurrent access to the same resources

Java programs can create multiple threads of execution from within the same program, using nothing but ordinary Java code. This is one of the outstanding features of the Java languages.

Multithreading an application is a topic that strikes fear into the hearts of new programmers. In old-fashioned languages such as C, this fear was more understandable. In Java, creating a new thread is no harder than creating an instance of other classes, after you learn a few rules of thumb. It is easier to get your program in a confused situation with threads, however, so be sure to learn what you are doing before becoming too ambitious.

In this chapter, we will take a look at why multiple threads of execution are used in some programs. Next, you will learn how to extend the java.lang.Thread class to create multiple threads. Following that, you will learn how to use the various methods of that class to control the threads that you create. Then, you will learn how to manage the problems associated with having two or more threads access the same data and methods. Finally, you will learn how to exchange data between two running threads.


    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: