[ Pobierz całość w formacie PDF ]
.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class HelloJava4extends JComponentimplements MouseMotionListener, ActionListener, Runnable {// Coordinates for the messageint messageX = 125, messageY = 95;String theMessage;JButton theButton;int colorIndex; // Current index into someColors.static Color[] someColors = { Color.black, Color.red,Color.green, Color.blue, Color.magenta };boolean blinkState;public HelloJava4(String message) {theMessage = message;theButton = new JButton("Change Color");setLayout(new FlowLayout( ));add(theButton);theButton.addActionListener(this); addMouseMotionListener(this);Thread t = new Thread(this);t.start( );}public void paintComponent(Graphics g) {g.setColor(blinkState ? getBackground() : currentColor( ));g.drawString(theMessage, messageX, messageY);}public void mouseDragged(MouseEvent e) {messageX = e.getX( );messageY = e.getY( );repaint( );}public void mouseMoved(MouseEvent e) {}public void actionPerformed(ActionEvent e) {// Did somebody push our button?if (e.getSource( ) == theButton)changeColor( );}synchronized private void changeColor( ) {// Change the index to the next color.if (++colorIndex == someColors.length)colorIndex = 0;setForeground(currentColor( )); // Use the new color.repaint( ); // Paint again so we can see the change.}synchronized private Color currentColor( ) {return someColors[colorIndex];}public void run( ) {try {while(true) {blinkState = !blinkState; // Toggle blinkState.repaint( ); // Show the change.Thread.sleep(500);}}catch (InterruptedException ie) {}}public static void main(String[] args) {JFrame f = new JFrame("HelloJava4");// Make the application exit when the window is closed.f.addWindowListener(new WindowAdapter( ) {public void windowClosing(WindowEvent we) { System.exit(0); }});f.setSize(300, 300);f.getContentPane( ).add(new HelloJava4("Hello, Java!"));f.setVisible(true);} }Compile and run this version of HelloJava just like the others.You'll see that the text does in factblink.Our apologies if you don't like blinking text we're not overly fond of it either but it doesmake for a simple, instructive example.2.4.1 ThreadsAll the changes we've made in HelloJava4 have to do with setting up a separate thread ofexecution to make the text blink.Java is a multithreaded language, which means there can bemany threads running at the same time.A thread is a separate flow of control within a program.Conceptually, threads are similar to processes, except that unlike processes, multiple threadsshare the same address space, which means that they can share variables and methods (butalso have their own local variables).Threads are also quite lightweight in comparison toprocesses, so it's conceivable for a single application to be running hundreds of threadsconcurrently.Multithreading provides a way for an application to handle many different tasks at the same time.It's easy to imagine multiple things going on at the same time in an application like a webbrowser.The user could be listening to an audio clip while scrolling an image; at the same time,the browser can be downloading an image.Multithreading is especially useful in GUI-basedapplications, as it improves the interactive performance of these applications.Unfortunately for us, programming with multiple threads can be quite a headache.The difficultylies in making sure routines are implemented so they can be run by multiple concurrent threads.Ifa routine changes the value of a state variable, for example, then only one thread should beexecuting the routine at a time.Later in this section, we'll examine briefly the issue of coordinatingmultiple threads' access to shared data.In other languages, synchronization of threads can beextremely complex and error-prone.You'll see that Java gives you a few simple tools that helpyou deal with many of these problems.Java threads can be started, stopped, suspended, andprioritized.Threads are preemptive, so a higher priority thread can interrupt a lower priority threadwhen vying for processor time.See Chapter 8, for a complete discussion of threads.The Java runtime system creates and manages a number of threads.(Exactly how varies with theimplementation.) We've already mentioned the repaint thread, which manages repaint( )requests and event processing for GUI components that belong to the java.awt andjavax.swing packages.Our example applications have done most of their work in one thread.Methods like mouseDragged( ) and actionPerformed( ) are invoked by the windowingthread and run on its time.Similarly, our constructor runs as part of the main application thread.This means we are somewhat limited in the amount of processing we do within these methods.Ifwe were, for instance, to go into an endless loop in our constructor, our application would neverappear, as it would never finish initializing.If we want an application to perform any extensiveprocessing, such as animation, a lengthy calculation, or communication, we should createseparate threads for these tasks.2.4.2 The Thread ClassAs you might have guessed, threads are created and controlled as Thread objects.An instanceof the Thread class corresponds to a single thread.It contains methods to start, control, and stopthe thread's execution.Our basic plan is to create a Thread object to handle our blinking code.We call the Thread's start( ) method to begin execution.Once the thread starts, it continuesto run until we call the Thread's interrupt( ) method to terminate it [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • personata.xlx.pl