CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Threads

Threads
Introduction
Classes and interfaces

Two ways to create a thread

  • Inherit the Thread class.
  • Implement the Runnable interface, then pass a reference to the Runnable object to the constructor of the Thread class. This is useful if the thread needs to inherit a class other than the Thread class.

Summary of classes and interfaces used for threading

Class/Interface Description
Thread A class that defines a thread. This class inherits the Object class and implements the Runnable interface.
Runnable An interface that must be implemented by any class whose objects are going to be executed by a thread. The only method in this interface is the run method.
Object The Object class has several methods that are used for threading.

Key methods for threading

Method Class/Interface Description
start Thread Registers this thread with the thread scheduler so it's available for execution.
run Runnable, Thread An abstract method that's declared by the Runnable interface and implemented by the Thread class. The thread scheduler calls this method to run the thread.
sleep Thread Causes the current thread to wait (sleep) for a specified period of time so the CPU can run other threads
wait Object Causes the current thread to wait until another thread calls the notify or notifyAll method for the current object.
notify Object Wakes up one arbitrary thread that's waiting on this object.
notifyAll Object Wakes up all the threads that are waiting on this object.
Previous | Concepts | How threads work | Typical uses for threads | Classes and interfaces | Life cycle | Next