Overview

Chapter 1 - Introduction to Threads

Java Thread Programming
Paul Hyde
  Copyright 1999 Sams Publishing

What Is a Thread?
When a modern operating system wants to start running a program, it creates a new process. A process is a program that is currently executing. Every process has at least one thread running within it. Sometimes threads are referred to as lightweight processes . A thread is a path of code execution through a program, and each thread has its own local variables , program counter (pointer to the current instruction being executed), and lifetime. Most modern operating systems allow more than one thread to be running concurrently within a process. When the Java Virtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be spawned (created).
Normally, you would think of Java code execution starting with the main() method and proceeding in a path through the program until all the statements in main() are completed. This is an example of a single thread. This main thread is spawned by the JavaVM, which begins execution with the main() method, executes all the statements in main() , and dies when the main() method completes.
A second thread is always running in the JavaVM: the garbage collection thread. It cleans up discarded objects and reclaims their memory. Therefore, even a simple Java program that only prints Hello World to System.out is running in a multithreaded environment: The two threads are the main thread and the garbage collection thread.
When a Java program includes a graphical user interface (GUI), the JavaVM automatically starts even more threads. One of these threads is in charge of delivering GUI events to methods in the program; another is responsible for painting the GUI window.
For example, imagine that a GUI-based programs main thread is performing a complex and long-running calculation and that while this is going on, the user clicks a Stop Calculation button. The GUI event thread would then invoke the event handling code written for this button, allowing the calculation thread to be terminated . If only one thread was present, both of these could not be done simultaneously , and interruption would be difficult.

Toc


Java Thread Programming
Java Thread Programming
ISBN: 0672315858
EAN: 2147483647
Year: 2005
Pages: 149
Authors: Paul Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net