giáo trình Java By Example phần 9 ppt

56 370 0
giáo trình Java By Example phần 9 ppt

Đ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

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. http://www.ngohaianh.info 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 It's important that your threads not dominate the computer's processor for longer than necessary. This is because other threads and processes are almost certainly in competition for the processor at the same time. If your thread will be running for a while, you should call the sleep() or yield() methods in order to give other processes a chance to run. This is more important on some systems than on others, but since you can't know for sure which system your applet will be running on, be a considerate thread programmer. Notice that the call to sleep() is enclosed in a try block and followed by a catch block that's watching for InterruptedException exceptions. You have to catch this exception because the sleep() method throws it. If you fail to catch the exception, your program will not compile. Deriving a Class from Thread The second way to create a thread is to derive a new class from Thread. Then, in your applet's class, you create and start a thread object of your thread class. This leaves you with two processes going simultaneously, the applet and the thread object created in the class. By giving the thread class access to data and methods in the applet, the thread can easily communicate with the applet in order to perform whatever tasks it was written for. Example: Creating a Thread Class Suppose that you want to write the same sort of applet as that shown in Listing 31.3, but now you want a separate thread to control the counting process. Listing 31.4 shows how you might write the new class for the thread. (Don't try to compile this code yet. You'll use it in the next example in this chapter.) http://www.ngohaianh.info Listing 31.4 MyThread.java: A Class Derived from Thread. public class MyThread extends Thread { ThreadApplet2 applet; int count; MyThread(ThreadApplet2 applet) { this.applet = applet; } public void run() { count = 0; while (count < 1000) { ++count; applet.displayStr = String.valueOf(count); applet.repaint(); try { http://www.ngohaianh.info sleep(100); } catch (InterruptedException e) { } } } } Derive the MyThread class from Thread. Declare the class's data fields, including a Thread object. Declare the class's constructor. Store the constructor's single parameter. Override 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. The first thing to notice in this thread class is that its constructor takes as a single argument a reference to a ThreadApplet2 object, which is the applet from which you'll be running this thread. The thread needs this reference so that it can communicate with the applet. Next, look at run(). The thread still counts from zero to one thousand, but now it accesses the applet object in order to create the display string and repaint the applet. In the original version of the program, the thread was directly associated with the class, rather than a completely separate process. Now that you have a new thread class, you'll want to call it up for active duty. You'll do that in the next example. Example: Using a Separate Thread in an Applet You'll now put that new thread class to work. To do this, you must have an applet that creates an object from the new thread class and calls that object's start() method to get the thread running. Listing 31.5 shows just such an applet, called ThreadApplet2. When you run the applet under Appletviewer, you'll see the same display that was created in the original version of the applet (ThreadApplet), but now the counting animation is being controlled by a separate thread class. http://www.ngohaianh.info 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 ThreadApplet2 extends Applet { MyThread thread; String displayStr; Font font; public void start() { font = new Font("TimesRoman", Font.PLAIN, 72); setFont(font); displayStr = ""; http://www.ngohaianh.info thread = new MyThread(this); thread.start(); } public void stop() { thread.stop(); } public void paint(Graphics g) { g.drawString(displayStr, 50, 150); } } Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Tell Java that the applet uses the MyThread class. Derive the ThreadApplet2 class from Applet. Declare the class's data fields, including a MyThread object. Override the start() method Create and set the applet's font. Initialize the display string. Create and start the thread. Override the stop() method. Stop the thread. Override the paint() method. Draw the applet's display string, which is the current count. http://www.ngohaianh.info Synchronizing Multiple Threads There may be times when you have several threads going, each competing for the same resources. This type of resource 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 keyword when you define a method (or even a code block). When you mark a method as synchronized, Java creates a monitor object for the class. The first time a thread calls the synchronized method, Java gives the monitor object to that thread. As long as the thread holds the monitor object, no other thread can enter the synchronized section of code. You can think of the monitor object as a key. Unless a thread is holding the key, it can't unlock the door to the synchronized method. Example: Using a Synchronized Method Using synchronized methods makes sense only when more than one thread is vying for an applet's resources. For that reason, to demonstrate thread synchronization, you need to create two threads. Listing 31.6 is a thread class, called MyThread2, that can count either forward or backward, depending upon the 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 MyThread2 extends Thread { ThreadApplet3 applet; boolean forward; int count; int increment; http://www.ngohaianh.info int end; int position; MyThread2(ThreadApplet3 applet, boolean forward) { this.applet = applet; this.forward = forward; } public void run() { InitCounter(); DoCount(); } protected void InitCounter() { if (forward) { count = 0; increment = 1; end = 1000; position = 120; http://www.ngohaianh.info } else { count = 1000; increment = -1; end = 0; position = 180; } } protected void DoCount() { while (count != end) { count = count + increment; String str = String.valueOf(count); applet.SetDisplayStr(str, position); try sleep(100); catch (InterruptedException e) http://www.ngohaianh.info { } } } } Derive the MyThread2 class from Thread. Declare the class's data fields. Declare the class's constructor. Store the constructor's parameters. Override the run() method Call the method that sets the values for this thread. Call the method that does the counting. Define the InitCounter() method. If the thread is to count forward Set the data fields for forward counting. Else if the thread is to count backwards Set the data fields for backwards counting. Define the DoCount() method. Loop until the counting is done. Increment the counter and set the display string. Go to sleep for one hundred milliseconds. When you construct a MyThread2 thread object, you must pass two values as parameters: a reference to the applet and a boolean value indicating whether the thread should count forward or backward. The thread uses the boolean value in its InitCounter() method to set the values needed to accomplish the counting. These values are the starting count value (count), the counting increment (increment), the target count (end), and the position at which to display the count in the applet (position). Notice that the increment variable can be either 1 or -1. When the increment gets added to the count, a positive increment increases the count by one, whereas a negative increment decreases the count by one. In its run() method, the thread calls the applet's SetDisplayStr() method, which, as you'll soon see, is the synchronized method. In other words, if the thread isn't holding the monitor object for SetDisplayStr(), it cannot enter the method. This prevents two running instances of the MyThread2 thread from trying to change the display string at the same time. Now it's time to look at the applet that's in charge of the threads. Listing 31.7 is the applet, which is called ThreadApplet3. This applet creates two objects of the MyThread2 class: one that counts forward and one that counts backward. The applet's SetDisplayStr() method is where the synchronization comes into play because both threads will be trying to access this method. http://www.ngohaianh.info [...]... Table 33.1 Java Development Tools Tool Description appletviewer This tool enables you to run Java applets without actually loading the applets into a Java- compatible browser This is the original Java- compatible Web browser hotjava java javac javadoc javah javap jdb This is the Java interpreter, which runs applets and applications by reading and interpreting byte-code CLASS files This is the Java compiler,... Chapter 32 Writing Java Applications CONTENTS q About Java Applications q The Simplest Java Application r r q Example: Building an Application Example: Getting an Application's Arguments Windowed Applications r Example: Changing an Applet to an Application r Understanding the FaceApp Application q Summary q Review Questions q 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... 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 http://www.ngohaianh.info example describes the entire process Example: Building an Application Building a Java application isn't any more difficult that building... http://www.ngohaianh.info Chapter 33 Development Tools Overview CONTENTS q The Tools q Using Appletviewer r Example: Loading More Than One Applet at a Time r Running the Debugger from Appletviewer q Using HotJava q Using Java' s Documentation Creator r Javadoc Tags r Example: Using Doc Tags r Example: Documenting an Applet r Javadoc Options q Using the Disassembler q Using the C Header Generator q Using the Debugger... applet's display, and how Java calls the action() method in response to some action by the user (for example, pressing Enter when typing in a TextField object) In this chapter, you'll extend your knowledge of applets by looking more closely at the construction of an applet, as well as discovering some other methods that are important to Java applets The Simplest Java Applet The Java programming language... converts your Java source-code to byte-code files that the interpreter can understand This tool creates HTML-format documentation from Java source code files This tool produces header files for use with native methods This tool is the Java disassembler, which enables you to convert byte-code files into a program description This is the Java debugger The two most important tools in Table 33.1 are the Java compiler,... it's a good example of how much mileage you can get out of the Java language, it hasn't been kept up to date In fact, even though HotJava was the first Java- compatible browser, it can no longer load and run most current applets This is because, as the Java language progressed from its beta versions to the version 1.0 release, the HotJava browser was not kept up to date As a result, HotJava can load... 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. .. HotJava can load and run only applets that were created using the old version of Java A set of these applets come with HotJava so that you can check them out Figure 33.2, for example, shows HotJava running the Hang Duke applet Figure 33.2 : HotJava can only run applets that were created with the early beta version of Java http://www.ngohaianh.info . controlled by a separate thread class. http://www.ngohaianh.info NOTE To compile Listing 31.5, make sure you have both the MyThread .java and ThreadApplet2 .java files in your CLASSES folder. Java will. 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. 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

Ngày đăng: 22/07/2014, 16:21

Từ khóa liên quan

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

Tài liệu liên quan