Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Threads - Overview

  • on an operating system a running program is known as a process
  • a single process can have seperate runnable tasks called threads
  • a thread is a single sequential flow of control within a process
  • a thread is also referred to as a lightweight process
  • with a single-processor CPU, only one thread is executing at any given time
  • the CPU quickly switches between active threads giving the illusion that they are all executing at the same time (logical concurrency)
  • on multi-processor systems several threads are actually executing at the same time (physical concurrency)
  • multi-programming occurs when multiple programs or processes are executed
  • multi-threading occurs when concurrency exists amoung threads running in a single process (also referred to as multi-tasking)
  • Java provides support for multi-threading as a part of the language
  • support centers on the:
    • java.lang.Thread class
    • java.lang.Runnable interface
    • java.lang.Object methods wait(), notify(), and notifyAll
    • synchronized keyword
  • every Java program has at least one thread which is executed when main() is invoked
  • all user-level threads are explicitly constructed and started from the main thread or by a thread originally started from main()
  • when the last user thread completes any daemon threads are stopped and the application stops
  • a thread's default daemon status is the same as that of thread creating it
  • you can check the daemon status using isDaemon()
  • you can set the daemon status using setDaemon().

    You cannot change a thread's status after it has been started

  • main() daemon status is false
  • if you want all your threads to quit when main() completes you can set their status to daemon using setDaemon(true)
  • there are two basic ways to create and run threads
    1. by subclassing the Thread class
    2. by implementing the Runnable interface

Also see

Example Code

Overview Thread Class Runnable Interface Thread States Scheduling Ending a Thread
  Execution Synchronization Locking Protocols synchronized keyword wait() notify(), notifyAll()
  Thread Mechanics