Google
 

 

up previous next contents
Up: 3. Day 3: Standard Previous: 3.3 Java networking Next: 3.5 JavaBeans   Contents

Subsections

3.4 Threads

3.4.1 Objectives

  • Explain what threads are, how they work, and when to use them.
  • Create threads using the Thread class.
  • Create threads using the Runnable interface.
  • Describe thread states.
  • Understand the methods that are used when manipulating threads.

3.4.2 Applications without multiple threads

  • Many applications work without multiple threads of concurrency.
  • In this world, a sequence of actions is completed in a linear, one-thread-of-thought-at-a-time manner.
  • Java makes it easy for developers to create multiple threads that essentially run simultaneously. (How this really works depends on what operating system your application is running on.)
  • A thread is considered lightweight because it runs within the context of a full-blown program.

3.4.3 Thread states

  • new - an empty thread, with no system resources allocated; all you can do is start it.
  • runnable - the start() method is called, and the thread is not dead or in the ``not runnable'' state.
  • not runnable - sleep() is invoked, thread calls wait(), thread is blocking on I/O.
  • dead - the end of the run() method has been reached.

3.4.4 Creating a threaded class with thread

  • Extend the java.lang.Thread class and override its run() method.
  • The run() method defines the behavior of the thread while it is running.
  • When the run() method ends, the thread goes into the dead state.
  • As a developer, you call the start() method of the thread; the JVM calls the run() method.
  • Never call the run() method directly.

3.4.5 Creating a threaded class with the runnable interface

  • Cannot always extend the Thread class because of single inheritance.
  • Implement the java.lang.Runnable interface (must implement the run() method).
  • Include a Thread attribute in the class.
  • The run() method still defines the behavior of the thread while it is running.

3.4.6 Thread methods

  • sleep(long ms) - causes the thread to sleep for the specified number of milliseconds.
  • yield() - provides a hint to the scheduler that this doesn't have to run at the current time, so the scheduler can choose another thread to run if need be.
  • join() - used to let one thread wait for another to terminate.
  • interrupt() - used to request that the thread cancel itself.
  • notifyAll() - wakes up all waiting threads.
  • wait() - used to pause the thread, presumably while it waits for some condition to be satisfied.

3.4.7 Thread references

  • The Java Programming Language - excellent chapter on threads.
  • Sun's Java Tutorial, at http://java.sun.com/docs/books/tutorial/, or more specifically http://java.sun.com/docs/books/tutorial/essential/threads/index.html.