Java 2 Exam Cram

Java 2 Exam Cram

by Bill Brogden
     
 
Serves as the perfect complement to all study guides and training materials for the Sun Certified Java 2 Programmer Exam. The best way to build confidence is through study of example questions similar to those on the real exam and this book will have numerous examples and a complete practice exam. Includes sections on proven test-taking strategies, warnings on trick

Overview

Serves as the perfect complement to all study guides and training materials for the Sun Certified Java 2 Programmer Exam. The best way to build confidence is through study of example questions similar to those on the real exam and this book will have numerous examples and a complete practice exam. Includes sections on proven test-taking strategies, warnings on trick questions, time-saving study tips, multiple-part question strategies, and shortcuts. Provides a special Cram Sheet with tips, acronyms, and memory joggers that readers can use for quick review before the exam. The most recent estimates indicate that there are 700,000 Java programmers worldwide, a huge potential audience. Universities and technical schools have just begun to teach Java programming, so achieving Sun Certified Java Programmer status is the best way to prove your Java programming skills. Even experienced Java programmers worry about failing the test because it emphasizes language basics, which most programmers handle by habit. Closely following the announced objectives for the exam, the book covers those features of the Java language which Sun considers to be essential, Java language syntax, structure, and basic constructs. Heavily emphasizes sample test questions to prepare the reader for the actual test.

Product Details

ISBN-13:
9781576102916
Publisher:
Coriolis Group
Publication date:
04/28/1999
Series:
Exam Cram 2 Series
Edition description:
Older Edition
Pages:
388
Product dimensions:
6.03(w) x 8.98(h) x 1.00(d)

Read an Excerpt


Chapter 9: Java Threads

Terms you'll need to understand:
  • Thread
  • Runnable
  • Synchronized
  • Monitor
  • Lock
  • InterruptedException
  • Deadlock

Techniques you'll need to master:

  • Writing code that starts a new thread of execution
  • Understanding the requirements of the Runnable interface
  • Knowing all the states a Thread object can exist in and the transitions it can undergo
  • Writing code that uses the synchronized keyword
  • Writing code that uses wait and notify or notifyAll to coordinate access to objects by Threads

Everything that happens in a Java program is the result of a thread executing a method associated with an object. Although Java provides many tools for manipulating threads, Java's portability has limitations because of variations in the underlying operating systems. It is essential for a Java programmer to understand both the power and limitations of Java threads.

Thread Background

One of the most striking features of Java is the ease with which a programmer can use multiple threads of execution. In C or C++, implementing multiple threads may involve you in a proprietary and platform-specific toolkit, using concepts that have been tacked on to the original language. Java, by contrast, was designed from the start to accommodate multiple threads.

Multithreading Vs. Multitasking

In modern operating systems, such as Windows 95, each program appears to run independently of all other programs. Although the CPU can do only one thing at a time, the operating system accomplishes multitasking by switching its attention so rapidly between the different applications that the applications appear to be running simultaneously. The operating system also prevents conflicts in the use of memory and other resources by the various programs.

In multithreading, multiple processes exist within a single program. If you use a modern Web browser, you have probably seen multithreading in action as the browser appears to load text and multiple images simultaneously. In the browser, each thread of execution tries to load a separate resource, so the overall loading process does not have to wait for a slow server response.

In the Java multithreaded environment, the Java Virtual Machine (JVM) objects and resources can be accessed by many separate threads. Each thread has its own path of execution but can potentially access any object in the program. It is up to the programmer to ensure that the threads do not interfere with each other. The Java language has built-in constructs that make this relatively easy, but you will need to put some effort into becoming comfortable with multithreading.

The Java language specification does not say how the JVM should implement multithreading. Because there is so much variation among the various operating systems and hardware on which Java is expected to run, the language specification leaves the specific implementation up to JVM designers. The Java Thread class describes the required behavior of Thread objects.

The Thread Class

Thread objects are used to encapsulate and conceal the details of a particular operating system's approach to multithreading. The JVM creates and runs several Threads to support even the simplest Java program. The Threads are used to load class files, interpret operating system events, and start the execution of your program.

The Life Of A Thread

Thread objects have a distinct life cycle with four basic states: new, runnable, blocked, and dead (see Figure 9.1). The transitions from new to runnable and from runnable to dead are simple and permanent; the transitions between runnable and blocked occupy most of the Java programmer's attention.

A Thread in the runnable state can resume execution at the whim of the Thread scheduler in the JVM. Moving a Thread from the running to the ready state is also up to the Thread scheduler. Java also uses the term Runnable when referring to the Runnable interface. When referring to the interface, I will show the word in bold with the first letter capitalized. Running Threads can be moved to and from the blocked state by various circumstances.

Thread Creation

Thread objects are created by constructor methods, just like any other object. A Thread just created by new is essentially an empty object; it does not yet have any operating system resources and can only be started. When a Thread is started, it gets connected to the JVM scheduling mechanism and executes a method declared as follows:

public void runo

This method can be the run method of the Thread class, the overriding run method of a class extending Thread, or the run method of a class that implements the Runnable interface.

A number of different Thread constructors exist, including some that let you create named Threads and assign Threads to ThreadGroup objects. However, the use of names and ThreadGroup objects is not among the objectives for the exam, so the interested student will have to investigate other sources. Here are the two types of constructors to consider:

1. Thread myT = new Thread();
2. Thread myT = new Thread( Runnable r );

Line 1 shows the construction of a plain Thread. Actually, plain Threads are not useful for anything because the run method in the Thread class is empty, but classes extending Thread can be quite useful. Line 2 shows the creation of a Thread with a reference to an object that implements the Runnable interface. When started, this Thread will execute the run method in the Runnable object.

The Runnable Interface

The Runnable interface is simple. A class implementing Runnable need only provide a method declared as:

public void runo

Any Thread attached to an object implementing Runnable will execute the run method of that object. It is possible to attach more than one Thread to a Runnable object.

Starting A Thread

A Thread does not do anything until its start method is executed. When a Thread is started, the JVM sets up some resources and puts the Thread in the list of runnable Threads. Exactly when a Thread gets to execute depends on its priority, the activity of other Threads, and the characteristics of the particular JVM.

You can simultaneously create and start a Thread as in the following method:

public void startThread() {
   new Thread(this).start();
}

You might think that the new Thread in the preceding example would be garbage-collected because no reference to it is being kept, but the JVM created a reference in its list of Threads. After Thread A has called Thread B's start method, you have no way of knowing whether A will continue to execute or B will start immediately. Make sure you have set up everything for Thread B before calling its start method.

Thread Priorities

Thread objects have an instance variable, priority, that has integer values from 1 to 10, with 10 being the most urgent. The JVM Thread scheduler always attempts to allow the highest priority available Thread to execute, but this is not guaranteed. The constants MIN_PRIORITY, MAX_PRIORITY, and NORM_PRIORITY are defined in the Thread class with values 1, 10, and 5. It is considered good form to use these constants rather than integer literals when using the setPriority method.
Study Alert    A newly created Thread inherits the priority of the Thread that creates it, not NORM_PRIORITY. If you want to have a particular priority, you should call setPriority before starting the Thread.
The JVM may adjust the priority downward to match the underlying operating system, so don't be surprised if the getPriority method returns a value different from the one you requested.

Death Of A Thread

When a Thread exits the run method to which it is attached, it becomes a dead Thread. This may occur because of a normal return from the run method or from an exception that is not caught. A dead Thread cannot be restarted.

Killing A Thread

In the first version of the Java language, the instance method stop was used to cause a Thread to stop what it was doing and die. In JDK 1.2, using stop is no longer recommended. (See the discussion later in the "Some Deprecated Methods" section.) ...

Meet the Author


Bill Brogden (Austin, TX) is a Java expert who has worked with Java since 1995. As sysop on the CompuServe Java forum he has helped many newcomers to Java. A student of many computer languages, he switched careers from environmental chemistry to software consultant at the start of the microcomputer revolution. He and his wife live in the countryside outside Austin, Texas with lots of computers and lots of dogs.

Customer Reviews

Average Review:

Write a Review

and post it to your social network

     

Most Helpful Customer Reviews

See all customer reviews >