Java By Example PHẦN 9 ppsx

59 207 0
Java By Example PHẦN 9 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

compile the program. Other exceptions-those that may be generated at runtime by more unpredictable problems like referencing a null pointer or dividing by zero-don't have to be handled in your program. However, a good programmer will design his or her applet so that common exceptions are handled where appropriate. Review Questions 1. How do you use a try program block? 2. How do you use a catch program block? 3. Do you have to catch all types of exceptions that might be thrown by Java? 4. When a method you call is defined as potentially throwing an exception, do you have to handle that exception in your program? 5. How many exceptions can you associate with a single try block? 6. How do you pass an exception up from a called method to the calling method? 7. What are the two main types of exceptions that Java may throw? Review Exercises 1. Write an applet that creates a button object. Set up exception-handling code for the OutOfMemoryException exception that could possibly occur when Java tries to allocate resources for the button. 2. Write an applet that catches all Exception objects and displays the string returned by the Exception object's getMessage() method. (Not all Exception objects return message strings. Test your program by generating a divide-by-zero error, which will cause Java to throw an ArithmeticException exception. This exception does generate a message string.) You can find the solution to this exercise in the CHAP30 folder of this book's CD-ROM. The applet is called ExceptionApplet4. Figure 30.8 shows what the applet looks like while running under Appletviewer. Figure 30.8 : ExceptionApplet4 displays the message string returned by an Exception object's getMessage() method. 3. Write an applet that enables the user to enter values into an array. Use two TextField objects, the first being where the user shouldenter the index at which to place the value, and the second being the value to add to the array. Set up the applet so that it responds to ArrayIndexOutOfBoundsException and NumberFormatException exceptions. You can find the solution to this exercise in the CHAP30 folder of this book's CD-ROM. The applet is called ExceptionApplet5. Figure 30.9 shows what the applet looks like while running under Appletviewer. Figure 30.9 : This is ExceptionApplet5 running under Appletviewer. Chapter 31 Threads CONTENTS ● Two Kinds of Threads ● Converting a Class to a Thread ❍ Declaring the Class as Implementing the Runnable Interface ❍ Implementing the run() Method ❍ Declaring a Thread Object ❍ Creating and Starting the Thread Object ❍ Stopping the Thread ❍ Example: Using a Thread in an Applet ● Deriving a Class from Thread ❍ Example: Creating a Thread Class ❍ Example: Using a Separate Thread in an Applet ● Synchronizing Multiple Threads ❍ Example: Using a Synchronized Method ❍ Understanding ThreadApplet3 ● Summary ● Review Questions ● Review Exercises When using Windows 95 (and other modern operating systems), you know that you can run several programs simultaneously. This ability is called multitasking. What you may not know is that many of today's operating systems also allow threads, which are separate processes that are kind of a step down from a complete application. A thread is a lot like a subprogram. An applet can create several threads- several different flows of execution-and run them concurrently. This is a lot like having multitasking inside multitasking. The user knows that he or she can run several applications at a time. The programmer knows that each application can run several threads at a time. In this chapter, you'll learn how to create and manage threads in your own applets. Two Kinds of Threads In Java, you can create threads in a couple of ways. The simplest way is to take an existing class and turn it into a thread. You do this by modifying the class so that it implements the Runnable interface, which declares the run() method required by all types of threads. (The run()method contains the code to be executed by a thread.) In the previous chapter, you learned how interfaces in Java enable you to add capabilities to classes simply by implementing the interface in that class. Now, you get a chance to put that idea to work for real. The second way to create a thread is to write a completely separate class derived from Java's Thread class. Because the Thread class itself implements the Runnable interface, it already contains a run() method. However, Thread's run() method doesn't do anything. You usually have to override the method in your own class in order to create the type of thread you want. Converting a Class to a Thread As I mentioned in the preceding section, the first way to create a thread is to convert a class to a thread. To do this, you must perform several steps, as listed here: 1. Declare the class as implementing the Runnable interface. 2. Implement the run() method. 3. Declare a Thread object as a data field of the class. 4. Create the Thread object and call its start() method. 5. Call the thread's stop() method to destroy the thread. The following sections look at each of these steps in detail. Declaring the Class as Implementing the Runnable Interface As you can see in step 1 in the preceding section, to create a thread from a regular class, the class must first be declared as implementing the Runnable interface. For example, if your class is declared as public class MyApplet extends Applet you must change that declaration to public class MyApplet extends Applet implements Runnable Implementing the run() Method Now, because you've told Java you're about to implement an interface, you must implement every method in the interface. In the case of Runnable, that's easy because there's only one method, run(), the basic implementation of which looks like this: public void run() { } When you start your new thread, Java calls the thread's run() method, so it is in run() where all the action takes place. The preceding example of the run() method is the minimum you need to compile the new source code for the thread. However, in a real program, you'll add code to run() so that the thread does what you want it to do. Declaring a Thread Object The next step is to declare a Thread object as a data field of the class, like this: Thread thread; The thread object will hold a reference to the thread with which the applet is associated. You will be able to access the thread's methods through this object. Creating and Starting the Thread Object Now it's time to write the code that creates the thread and gets it going. Assuming that your new threaded class is an applet, you'll often want to create and start the thread in the applet's start() method, as shown in Listing 31.1. Listing 31.1 LST31_1.TXT: Creating and Starting a Thread Object. public void start() { thread = new Thread(this); thread.start(); } NOTE Back in Chapter 15, "Writing a Simple Applet," you learned that start() is the method that represents the applet's second life- cycle stage. Java calls your applet's life-cycle methods in this order: init(), start(), paint(), stop(), and destroy(). Java calls the start() method whenever the applet needs to start running, usually when it's first loaded or when the user has switched back to the applet from another Web page. Look at the call to the Thread constructor in Listing 31.1. Notice that the constructor's single argument is the applet's this reference. This is how Java knows with which class to associate the thread. Right after the call to the constructor, the applet calls the Thread object's start() method, which starts the thread running. When the thread starts running, Java calls the thread's run() method, where the thread's work gets done. Stopping the Thread When the thread's run() method ends, so does the thread. However, because threads tend to run for quite a while, controlling things like animation in the applet, the user is likely to switch away from your applet before the thread stops. In this case. it's up to your applet to stop the thread. Because Java calls an applet's stop() method whenever the user switches away from the applet, the stop() method is a good place to stop the thread, as shown in Listing 31.2. Listing 31.2 LST31_2.TXT: Stopping a Thread. public void stop() { thread.stop(); } Example: Using a Thread in an Applet To understand about threads, you really have to dig in and use them. So in this section, you'll put together an applet that associates itself with a Thread object and runs the thread to control a very simple animated display. The animation in this case is not a bunch of space invaders landing to take over the earth, but rather only a changing number that proves that the thread is running. Listing 31.3 is the applet in question, which is called ThreadApplet. Figure 31.1 shows the applet running under Appletviewer. Figure 31.1 : ThreadApplet uses a thread to count to 1,000. Listing 31.3 ThreadApplet.java: Using a Thread in an Applet. import java.awt.*; import java.applet.*; public class ThreadApplet extends Applet implements Runnable { Thread thread; int count; String displayStr; Font font; public void start() { font = new Font("TimesRoman", Font.PLAIN, 72); setFont(font); count = 0; displayStr = ""; thread = new Thread(this); thread.start(); } public void stop() { thread.stop(); } public void run() { while (count < 1000) { ++count; displayStr = String.valueOf(count); repaint(); try { thread.sleep(100); } catch (InterruptedException e) { } } } public void paint(Graphics g) { g.drawString(displayStr, 50, 130); } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive ThreadApplet from Applet and implement Runnable. Declare the class's data fields, including a Thread object. Override the start() method. Create and set the applet's display font. Initialize data fields. Create and start the thread. Override the stop() method. Stop the thread. Implement the run() method Loop one thousand times. Increment the counter. Create the display string from the counter. Tell Java to repaint the applet. Suspend the thread for one hundred milliseconds. Override the paint() method. Draw the display string. There are a couple of interesting things in ThreadApplet of which you should be aware. First, notice that in run(), the thread loops one thousand times, after which the while loop ends. When the while loop ends, so does the run() method. This means that when you run ThreadApplet, if you let it count all the way to one thousand, the thread ends on its own. However, what if you switch to a different Web page before ThreadApplet has counted all the way to one thousand? Then, Java calls the applet's stop() method, which ends the thread by calling the thread's stop() method. The next point of interest is what's going on inside run(). At the beginning of the loop, the program increments the counter, converts the counter's value to a string, and then repaints the applet so that the new count value appears in the window. That code should be as clear as glass to you by now. But what's all that malarkey after the call to repaint()? That's where the thread not only times the animation, but also relinquishes the computer so that other threads get a chance to run. Simply, the call to the thread's sleep() method suspends the thread for the number of milliseconds given as its single argument. In this case, the sleep time is 100 milliseconds, or one tenth of a second. If you want the animation to run faster, change the 100 to a smaller value. To count slower, change the 100 to a larger value. CAUTION [...]... the counting animation is being controlled by a separate thread class NOTE To compile Listing 31.5, make sure you have both the MyThread .java and ThreadApplet2 .java files in your CLASSES folder Java will then compile both files when you compile ThreadApplet2 .java Listing 31.5 ThreadApplet2 .JAVA: An Applet That Creates a Separate Thread import java. awt.*; import java. applet.*; import MyThread; public class... Chapter 32 Writing Java Applications CONTENTS q q q q q q About Java Applications The Simplest Java Application r Example: Building an Application r Example: Getting an Application's Arguments Windowed Applications r Example: Changing an Applet to an Application r Understanding the FaceApp Application Summary Review Questions Review Exercises The bulk of this book is dedicated to using Java to create applets... learn the basics of creating standalone applications with Java About Java Applications If you've run the HotJava browser, you've already had experience with Java applications The HotJava browser was programmed entirely in Java and, although the browser is way out of date at the time of this writing, it demonstrates how much you can do with Java, even when dealing with sophisticated telecommunications... text by using the println() method of the System.out package To run the Java application, you must first compile it and then run the byte-code file using Java' s interpreter You compile the program exactly as you would an applet, using javac The following example describes the entire process Example: Building an Application Building a Java application isn't any more difficult that building an applet, although... applications For example, because Java applications aren't run "on the Web," they don't have to deal with all the security issues that come up when running applets A Java application can access any files it needs to access, for example If you've ever programmed in C or C++, you'll discover that writing applications in Java is similar If you haven't programmed in those languages, rest assured that, by this point... values you give to the class's constructor By creating two thread objects from this class, you can experiment with thread synchronization NOTE To compile Listings 31.6 and 31.7, make sure you have both the MyThread2 .java and ThreadApplet3 .java files in your CLASSES folder Java will then compile both files when you compile ThreadApplet3 .java Listing 31.6 MyThread2 .java: A Double-Duty Thread public class... you already have 95 % of the knowledge you need in order to write standalone Java applications The Simplest Java Application You can create a runnable Java application in only a few lines of code In fact, an application requires only one method called main().C and C++ programmers will recognize main() as being the place where applications begin their execution The same is true for Java applications... Listing 32.1 shows the simplest Java application Listing 32.1 SimpleApp .java: The Simplest Java Application class SimpleApp { public static void main(String args[]) { System.out.println("My first Java app!"); } } Declare the SimpleApp class Declare the app's main() method Print a line of text on the screen If you look a the first line of Listing 32.1, you'll see that even a Java standalone application... competition can be deadly for threads For example, what if one thread tries to read from a string while another thread is still writing to that string? Depending on the situation, you'll get strange results You can avoid these problems by telling Java where synchronization problems may occur so that Java can keep an eye out for unhealthy thread competition To put Java on guard, you use the synchronized... create applets for the Internet However, Java is a fullfledged computer language that enables you to write complete, stand-alone applications Although most Java users are interested in creating only applets (there are other, more powerful languages for creating applications), no introductory Java book would be complete without at least dabbling a little with Java applications In this chapter, then, . returned by the Exception object's getMessage() method. (Not all Exception objects return message strings. Test your program by generating a divide -by- zero error, which will cause Java to. being controlled by a separate thread class. NOTE To compile Listing 31.5, make sure you have both the MyThread .java and ThreadApplet2 .java files in your CLASSES folder. Java will then compile. both files when you compile ThreadApplet2 .java. Listing 31.5 ThreadApplet2 .JAVA: An Applet That Creates a Separate Thread. import java. awt.*; import java. applet.*; import MyThread; public class

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Mục lục

  • Java By Example

    • Chapter 31-- Threads

    • Chapter 32 -- Writing Java Applications

    • Chapter 33 -- Development Tools Overview

    • Chapter 34 -- Using the Compiler

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan