Home > Articles > Programming > Java

A Programmer's Guide to Java SCJP Certification: Threads

  • Print
  • + Share This
This chapter describes threads, thread states, and thread behavior to help prepare for the Java SCJP Certification exam.
This chapter is from the book

13.1 Multitasking

Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:

  • Process-based multitasking
  • Thread-based multitasking

At the coarse-grain level there is process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor. At the fine-grain level there is thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word-processor that is printing and formatting text at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program concurrently. The sequence of code executed for each task defines a separate path of execution, and is called a thread (of execution).

In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted, for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.

Some advantages of thread-based multitasking as compared to process-based multitasking are:

  • threads share the same address space
  • context switching between threads is usually less expensive than between processes
  • the cost of communication between threads is relatively low

Java supports thread-based multitasking and provides high-level facilities for multithreaded programming. Thread safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.

  • + Share This
  • 🔖 Save To Your Account