Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

setLookAndFeel method of class UIManager

setMajorTickSpacing method of class JSlider

setMnemonic method of class AbstractButton

setOpaque method of class JComponent

setPaintTicks method of class JSlider

setSelected method of class AbstractButton

setVerticalScrollBarPolicy method of JSlider

[Page 1049]

shortcut key

show method of class JPopupMenu snap-to ticks for JSlider

SOUTH constant of class GridBagConstraints SOUTHEAST constant of class GridBagConstraints SOUTHWEST constant of class GridBagConstraints stateChanged method of interface

ChangeListener

submenu

SwingUtilities class

thumb of JSlider

tick marks on JSlider

title bar

transparency of a JComponent

UIManager class

updateComponentTreeUI method of class

SwingUtilities

VERTICAL constant of class GridBagConstraints vertical strut

weightx field of class GridBagConstraints weighty field of class GridBagConstraints

WEST constant of class GridBagConstraints

window

window events

windowActivated method of interface

WindowListener

WindowClosing method of interface

WindowListener

WindowConstants interface

WindowDeactivated method of interface

WindowListener

WindowDeiconified method of interface

WindowListener

WindowIconified method of interface

WindowListener

WindowListener interface

WindowOpened method of interface

WindowListener

X_AXIS constant of class Box

Y_AXIS constant of class Box

[Page 1049 (continued)]

Self-Review Exercises

22.1 Fill in the blanks in each of the following statements:

a.The _____ class is used to create a menu object.

b.The _____ method of class JMenu places a separator bar in a menu.

c.JSlider events are handled by the _____ method of interface _____.

d.The GridBagConstraints instance variable _____ is set to CENTER by default.

22.2 State whether each of the following is true or false. If false, explain why.

a.When the programmer creates a JFrame, a minimum of one menu must be created and added to the JFrame.

b.The variable fill belongs to the GridBagLayout class.

c.Drawing on a GUI component is performed with respect to the (0, 0) upperleft corner coordinate of the component.

d.The default layout for a Box is BoxLayout.

22.3 Find the error(s) in each of the following and explain how to correct the error(s).

a.JMenubar b;

b.mySlider = JSlider( 1000, 222, 100, 450 );

c.gbc.fill = GridBagConstraints.NORTHWEST; // set fill

d.// override to paint on a customized Swing component public void paintcomponent( Graphics g )

{

g.drawString( "HELLO", 50, 50 ); } // end method paintComponent

e.// create a JFrame and display it

JFrame f = new

JFrame( "A Window" );

f.setVisible(

true );

[Page 1050]

Answers to Self-Review Exercises

22.1 a) JMenu. b) addSeparator. c) stateChanged, ChangeListener. d) anchor.

22.2 a. False. A JFrame does not require any menus.

b.False. The variable fill belongs to the GridBagConstraints class.

c.True.

d.True.

22.3 a. JMenubar should be JMenuBar.

b.The first argument to the constructor should be either

SwingConstants.HORIZONTAL or SwingConstants.VERTICAL, and the keyword new must be used after the = operator.

c.The constant should be either BOTH, HORIZONTAL, VERTICAL or NONE.

d.paintcomponent should be paintComponent, and the method should call super.paint-Component( g ) as its first statement.

e.The JFrame's setSize method must also be called to establish the size of the window.

[Page 1050 (continued)]

Exercises

22.4Fill in the blanks in each of the following statements:

a.A JMenuItem that is a JMenu is called a(n) _____

b.Method _____ attaches a JMenuBar to a JFrame.

c.Container _____ class has a default BoxLayout.

d.A(n) _____ manages a set of child windows declared with class

JInternalFrame.

22.5State whether each of the following is true or false . If false, explain why.

a.Menus require a JMenuBar object so they can be attached to a JFrame.

b.BoxLayout is the default layout manager for a JFrame.

c.Method setEditable is a JTextComponent method.

d.Class JFrame directly extends class Container.

e.JApplets can contain menus.

22.6Find the error(s) in each of the following. Explain how to correct the error(s).

a.x.add( new JMenuItem( "Submenu Color" ) );// create submenu

b.container.setLayout( m = new GridbagLayout() );

22.7Write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumference. Use the following equations: diameter = 2 radius, area = p radius2, circumference = 2 p radius. Use the constant

Math.PI for pi (p). All drawing should be done on a subclass of JPanel, and the results of the calculations should be displayed in a read-only JTextArea.

22.8Enhance the program in Exercise 22.7 by allowing the user to alter the radius with a JSlider. The program should work for all radii in the range from 100 to 200. As the radius changes, the diameter, area and circumference should be updated and displayed. The initial radius should be 150. Use the equations from Exercise 22.7. All drawing should be done on a subclass of JPanel, and the results of the calculations should be displayed in a read-only JTextArea.

22.9Explore the effects of varying the weightx and weighty values of the program in Fig. 22.21. What happens when a slot has a nonzero weight but is not allowed to fill the whole area (i.e., the fill value is not BOTH)?

22.10Write a program that uses the paintComponent method to draw the current value of a JSlider on a subclass of JPanel. In addition, provide a JTextField where a specific value can be entered. The JTextField should display the current value of the JSlider at all times. A JLabel should be used to identify the JTextField. The JSlider methods setValue and getValue should be used. [Note: The setValue method is a public method that does not return a value and takes one integer argument, the JSlider value, which determines the position of the thumb.]

[Page 1051]

22.11Modify the program in Fig. 22.13 by adding a minimum of two new tabs.

22.12Declare a subclass of JPanel called MyColorChooser that provides three JSlider objects and three JTextField objects. Each JSlider represents the values from 0 to 255 for the red, green and blue parts of a color. Use these values as the arguments to the Color constructor to create a new Color object. Display the current value of each JSlider in the corresponding JTextField. When the user changes the value of the JSlider, the JTextField should be changed accordingly. Use your new GUI component as part of an application that displays the current Color value by drawing a filled rectangle.

22.13Modify the MyColorChooser class of Exercise 22.12 to allow the user to enter an integer value into a JTextField to set the red, green or blue value. When the user presses Enter in the JTextField, the corresponding JSlider should be set to the appropriate value.

22.14Modify the application in Exercise 22.13 to draw the current color as a rectangle on an instance of a subclass of JPanel which provides its own paintComponent method to draw the rectangle and provides set methods to set the red, green and blue values for the current color. When any set method is invoked, the drawing panel should automatically repaint itself.

22.15Modify the application in Exercise 22.14 to allow the user to drag the mouse across the drawing panel (a subclass of JPanel) to draw a shape in the current color. Enable the user to choose what shape to draw.

22.16Modify the application in Exercise 22.15 to provide the user with the ability to terminate the application by clicking the close box on the window that is displayed and by selecting Exit from a File menu. Use the techniques shown in Fig. 22.5.

22.17(Complete Drawing Application) Using the techniques developed in this chapter and Chapter 11, create a complete drawing application. The program should use the GUI components from Chapter 11 and Chapter 22 to enable the user to select the shape, color and fill characteristics. Each shape should be stored in an array of MyShape objects, where MyShape is the superclass in your hierarchy of shape classes. Use a JDesktopPane and JInternalFrames to allow the user to create multiple separate drawings in separate child windows. Create the user interface as a separate child window containing all the GUI components that allow the user to determine the characteristics of the shape to be drawn. The user can then click in any JInternalFrame to draw the shape.

[Page 1052]

Chapter 23. Multithreading

Do not block the way of inquiry.

Charles Sanders Peirce

A person with one watch knows what time it is; a person with two watches is never sure.

Proverb

Learn to labor and to wait.

Henry Wadsworth Longfellow

The most general definition of beauty...Multeity in Unity.

Samuel Taylor Coleridge

The world is moving so fast these days that the man who says it can't be done is generally interrupted by someone doing it.

Elbert Hubbard

OBJECTIVES

In this chapter you will learn:

What threads are and why they are useful.

How threads enable you to manage concurrent activities.

The life cycle of a thread.

Thread priorities and scheduling.

To create and execute Runnables.

Thread synchronization.

What producer/consumer relationships are and how they are implemented with multithreading.

To display output from multiple threads in a Swing GUI.

About Callable and Future.

[Page 1053]

Outline

23.1 Introduction

23.2 Thread States: Life Cycle of a Thread

23.3 Thread Priorities and Thread Scheduling

23.4 Creating and Executing Threads

23.5 Thread Synchronization

23.6 Producer/Consumer Relationship without Synchronization

23.7 Producer/Consumer Relationship with Synchronization

23.8 Producer/Consumer Relationship: Circular Buffer

23.9 Producer/Consumer Relationship: ArrayBlockingQueue

23.10 Multithreading with GUI

23.11 Other Classes and Interfaces in java.util.concurrent

23.12 Monitors and Monitor Locks

23.13 Wrap-Up

Summary

Terminology

Self-Review Exercises

Answers to Self-Review Exercises

Exercises

[Page 1053 (continued)]

23.1. Introduction

It would be nice if we could perform one action at a time and perform it well, but that is usually difficult to do. The human body performs a great variety of operations in parallelor, as we will say throughout this chapter, concurrently. Respiration, blood circulation, digestion, thinking and walking, for example, can occur concurrently. All the sensessight, touch, smell, taste and hearingcan be employed at once. Computers, too, can perform operations concurrently. It is common for personal computers to compile a program, send a file to a printer and receive electronic mail messages over a network concurrently. Only computers that have multiple processors can truly execute operations concurrently. Operating systems on single-processor computers use various techniques to simulate concurrency, but on such computers only a single operation can execute at once.

Most programming languages do not enable programmers to specify concurrent activities. Rather, the languages generally provide control statements that only enable programmers to perform one action at a time, proceeding to the next action after the previous one has finished. Historically, concurrency has been implemented with operating system primitives available only to experienced systems programmers.

The Ada programming language, developed by the United States Department of Defense, made concurrency primitives widely available to defense contractors building military command-and-control systems. However, Ada has not been widely used in academia and commercial industry.

Java makes concurrency available to the applications programmer through its APIs. The programmer specifies that applications contain threads of execution, where each thread designates a portion of a program that may execute concurrently with other threads. This capability, called multithreading, gives the Java programmer powerful capabilities not available in the core C and C++ languages on which Java is based.

[Page 1054]

Performance Tip 23.1

A problem with single-threaded applications is that lengthy activities must complete before other activities can begin. In a multithreaded application, threads can be distributed across multiple processors (if they are available) so that multiple tasks are performed concurrently and the application can operate more efficiently. Multithreading can also increase performance on single-processor systems that simulate concurrencywhen one thread cannot proceed, another can use the processor.

Portability Tip 23.1

Unlike languages that do not have built-in multithreading capabilities (such as C and C++) and must therefore make nonportable calls to operating system multithreading primitives, Java includes multithreading primitives as part of the language itself and as part of its libraries. This facilitates manipulating threads in a portable manner across platforms.

We will discuss many applications of concurrent programming. For example, when programs download large files, such as audio clips or video clips, over the Internet, users may not want to wait until an

entire lengthy clip downloads before starting the playback. To solve this problem, we can put multiple threads to workone thread downloads the clip, and another plays it. These activities proceed concurrently. To avoid choppy playback, we synchronize the threads so that the player thread does not begin until there is a sufficient amount of the clip in memory to keep the player thread busy.

Another example of multithreading is Java's garbage collection. C and C++ require the programmer to reclaim dynamically allocated memory explicitly. Java provides a garbage-collector thread that reclaims memory which is no longer needed.

Writing multithreaded programs can be tricky. Although the human mind can perform functions concurrently, people find it difficult to jump between parallel trains of thought. To see why multithreading can be difficult to program and understand, try the following experiment: Open three books to page 1, and try reading the books concurrently. Read a few words from the first book, then read a few words from the second book, then read a few words from the third book, then loop back and read the next few words from the first book, and so on. After this experiment, you will appreciate the challenges of multithreadingswitching between books, reading briefly, remembering your place in each book, moving the book you are reading closer so you can see it and pushing books you are not reading asideand, amid all this chaos, trying to comprehend the content of the books!

Programming concurrent applications is a difficult and error-prone undertaking. Even some of the simplest concurrent applications are beyond the capability of beginner programmers. If you find that you must use synchronization in a program, you should follow some simple guidelines. First, use existing classes from the Java API (such as the ArrayBlockingQueue class discussed in Section 23.9, Producer/Consumer Relationship: ArrayBlockingQueue) that manage synchronization for you. The classes in the Java API have been fully tested and debugged and help you avoid common traps and pitfalls. Second, if you find that you need more custom functionality than that provided in the Java APIs, you should use the synchronized keyword and Object methods wait, notify and notifyAll (discussed in Section 23.12, Monitors and Monitor Locks). Finally, if you need even more complex capabilities, then you should use the Lock and Condition interfaces that are introduced in Section 23.5, Thread Synchronization).

The Lock and Condition interfaces are advanced tools and should be used only by advanced programmers who are familiar with the common traps and pitfalls of concurrent programming with synchronization. We explain these topics in this chapter for a number of reasons. For one, they provide a solid basis for understanding how concurrent applications synchronize access to shared memory. Even, if an application does not use these tools explicitly, the concepts are still important to understand. We have also discussed these topics to highlight the new concurrency features introduced by J2SE 5.0. Finally, by showing you the complexity involved in using these low-level features, we hope to impress upon you the importance of using prepackaged concurrent capabilities whenever possible.

[Page 1055]