Archive for September, 2007

880 Multithreading Chapter 15 Method ride guarantees that

Sunday, September 16th, 2007

880 Multithreading Chapter 15 Method ride guarantees that only one Personmay ride the Elevator at a time as described in Section 15.5, only one synchronizedmethod may be active on an object at once, so all other Person threads attempting to invoke ride must wait for the current thread to exit method ride. Method ride invokes static method sleep of class Thread to put the Person thread into the sleep state, which represents the Person waiting for the ride to complete. We must specify the maximum amount of time that a Person will wait for the Elevator to complete traveling however, there is no such information specified in the problem statement. We introduce a new attribute that represents this time maxTravelTime, to which we arbitrarily assign a value of 10 minutes (i.e., a Person will wait 10 minutes for the travel to complete). Attribute maxTravelTime is a safeguard in case the Elevator for whatever reason never reaches the other Floor. The Person should never have to wait this long if the Person waits 10 minutes, then the Elevator is broken, and we assume that our Person crawls out of the Elevator and exits the simulation. Software Engineering Observation 15.6 In a software-development process, the analysis phase yields a requirements document (e.g., our problem statement). As we continue the design and implementation phase, we discover additional issues that were not apparent to us at the analysis phase. As designers, we must anticipate these issues and deal with them accordingly. Software Engineering Observation 15.7 One false assumption to make is that the system requirements remain stable (i.e., they provide all information necessary to build the system) throughout the analysis and design phases. In large systems that have long implementation phases, requirements can, and often do, change to accommodate those issues that were not apparent during analysis. If our Elevator works correctly, the Elevator travels for five seconds specifically, invoking method sleep halts the Elevator s thread for five seconds to simulate the travel. When the Elevator thread awakens, it sends elevatorArrived events as described in Section 10.22. The elevatorDoor receives this event and invokes method doorOpened (message 3.3) of the ridingPassenger, as in: public void doorOpened( DoorEvent doorEvent ) { // set Person on Floor where Door opened setLocation( doorEvent.getLocation() ); // interrupt Person’s sleep method in run method and // Elevator’s ride method interrupt(); } Method doorOpened sets the ridingPassenger s Location to the Floorat which the Elevator arrived, then calls the ridingPassenger thread s interrupt method. The interrupt method terminates the sleep method invoked in method ride, method ride terminates, and the ridingPassenger leaves the Elevator, then exits the simulation. When the ridingPassenger exits the Elevator, the ridingPassenger releases the monitor on the Elevator object, which allows the waitingPassenger to invoke the ride method and obtain the monitor. Now, the waitingPassenger may invoke method ride to ride the Elevator.
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Chapter 15 Multithreading 879 (DoorEvent) 3.2.1 : doorOpened(

Saturday, September 15th, 2007

Chapter 15 Multithreading 879 <
> (DoorEvent) 3.2.1 : doorOpened( ) 3.2 : openDoor( ) firstFloorLight : Light elevatorDoor : Door : ElevatorShaft : Elevator : Bell firstFloorButton : Button elevatorButton : Button waitingPassenger : Person firstFloorDoor : Door ridingPassenger : Person 4.2.1 : turnOnLight( )4.1.1 : resetButton( ) 3.3.1 : exitElevator( ) 4 : elevatorArrived( ) 3 : elevator Arrived( ) 3.3 : doorOpened( ) 3.1 : openDoor( ) 1 : elevatorArrived( ) 1.1 : resetButton( ) 2 : elevator Arrived( ) 4.1 : elevatorArrived( ) 4.2 : elevatorArrived( ) 3.2.1.2 : ride( ) {concurrent} 3.3.1 / 3.2.1.1 : enterElevator( ) 2.1 : ringBell( ) <
> (ElevatorMoveEvent) <
> (Location) Fig. 15.8Modified collaboration diagram with active classes for passengers 15. entering and exiting the Elevator. public synchronized void ride() { try { Thread.sleep( maxTravelTime ); } catch ( InterruptedException interruptedException ) { // method doorOpened in Person interrupts method sleep; // Person has finished riding Elevator } }
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

878 Multithreading Chapter 15 (Email web hosting) In Thinking About Objects

Saturday, September 15th, 2007

878 Multithreading Chapter 15 In Thinking About Objects Section 10.22, we encountered a problem with the collaboration diagram of Fig. 10.26 the waitingPassenger (the Person waiting to ride the Elevator) always enters the Elevator before the ridingPassenger (the Person riding the Elevator) exits. Proper use of multithreading in Java avoids this problem by guaranteeing that the waitingPassenger must wait for the ridingPassenger to exit the Elevator as would happen in real life. In our collaboration diagrams, objects pass messages to other objects by calling methods of those other objects a sending object may proceed only after a method returns. Java refers to such a message pass as a synchronous call. However, the synchronous call is not synchronized, because several objects may access the method at the same time the synchronous call cannot guarantee exclusivity to one object. This poses a problem when we model our elevator simulation, because according to Fig. 10.26, the waitingPassenger and the ridingPassenger may occupy the Elevator at the same time, which violates the capacity-of-one requirement specified in the problem statement. In this section, we use a synchronizedmethod to guarantee that only one Person may occupy the Elevator at a time. Threads, Active Classes and Synchronized Methods Java uses threads flows of program control independent of other flows to represent independent, concurrent activities. The UML provides the notion of an active class to represent a thread. Classes Elevator and Person are active classes (threads), because their objects must be able to operate concurrently and independently of one another and of other objects in the system. For example, the Elevator must be able to move between Floors while a Personis walking on a Floor. Figure 15.8 updates the collaboration diagram of Fig. 10.26 to support active classes, which are denoted by a thick black border in the diagram. To ensure that Persons enter and exit the Elevator in the proper order, we require a specific order in which to send messages the Elevator must send message 3.3.1 (ridingPassenger exits) before sending message 3.2.1.1 (waiting- Passenger enters the Elevator). The UML provides a notation to allow synchronization in collaboration diagrams if we have two messages A and B, the notation B/A indicates that message A must wait for B to complete before message A occurs. For example, the 3.3.1/3.2.1.1 notation before the enterElevator message indicates that waitingPassengermust wait for ridingPassengerto exit the Elevator (message 3.3.1) before entering (message 3.2.1.1). Software Engineering Observation 15.5 Messages in collaboration diagrams must complete in order (e.g., message 3.1 must complete before issuing message 3.2). However, messages between active classes may specify different ordering as necessary to guarantee synchronization between certain messages. A Person must synchronize with the Elevator when traveling to guarantee that only one Person occupies the Elevator at a time. In Fig. 15.8, we include the ride message (3.2.1.2) to represent the Person riding the Elevatorto the other Floor. The {concurrent} keyword placed after the ride message indicates that method rideis synchronized when we implement our design in Java. The Elevator contains method ride for the Person to allow the synchronization.
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

1 on 1 web hosting - Chapter 15 Multithreading 877 The constructor public Thread(

Friday, September 14th, 2007

Chapter 15 Multithreading 877 The constructor public Thread( ThreadGroup threadGroup, Runnable runnableObject ) constructs a Thread that belongs to threadGroup and that invokes the run method of runnableObject when the thread is assigned a processor to begin execution. The constructor public Thread( ThreadGroup threadGroup, Runnable runnableObject, String stringName ) constructs a Thread that belongs to threadGroup and that invokes the run method of runnableObject when the thread is assigned a processor to begin execution. The name of this Thread is indicated by stringName. Class ThreadGroup contains many methods for processing groups of threads. Some of these methods are summarized here. For more information on these methods, see the Java API documentation. 1. Method activeCount reports the number of active threads in a thread group plus the number of active threads in all its child thread groups. 2. Method enumerate has four versions. Two versions copy into an array of Thread references the active threads in the ThreadGroup (one of these also allows you to recursively get copies of all the active threads in child Thread- Group). Two versions copy into an array of ThreadGroup references the active child thread groups in the ThreadGroup (one of these also allows you to recursively get copies of all the active thread groups in all the child Thread- Groups). 3. Method getMaxPriority returns the maximum priority of a ThreadGroup. Method setMaxPrioritysets a new maximum priority for a ThreadGroup. 4. Method getName returns as a Stringthe ThreadGroup s name. 5. Method getParent determines the parent of a thread group. 6. Method parentOf returns true if the ThreadGroup to which the message is sent is the parent of, or the same as, the ThreadGroup supplied as an argument and returns false otherwise. Testing and Debugging Tip 15.5 Method list lists the ThreadGroup. This can help in debugging. 15.12 (Optional Case Study) Thinking About Objects: Multithreading Real-world objects perform their operations independently of one another and concurrently (in parallel). As you learned in this chapter, Java is a multithreaded programming language that facilitates the implementation of concurrent activities. The UML also contains support for designing concurrent models, as we will see shortly. In this section, we discuss how our simulation benefits from multithreading.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

876 Multithreading Chapter 15 is being resumed. If

Friday, September 14th, 2007

876 Multithreading Chapter 15 is being resumed. If the appropriate boolean variable is false, the program calls method notifyAll (line 106) to move all waiting threads into the ready state and prepare them to resume execution. When each thread is dispatched to the processor to resume execution, the while condition at lines 139 140 in the run method fails for the resumed thread and the loop terminates. Execution of the run method then continues from line 156. For any other threads that became ready, but still are suspended, the condition at lines 139 140 remains true and the threads reenter the waiting state. The applet s stop method (lines 79 90) is provided to stop all three threads if the user leaves the Web page on which this applet resides (you can simulate this by selecting Stop from the appletviewer s Applet menu). The for loop at lines 84 85 sets each Thread reference in array threadsto null. Line 89 invokes Object method notifyAll to ensure that all waiting threads get ready to execute. When the program encounters the while loop condition at line 129 for each thread, the condition fails and the run method terminates. Thus, each thread dies. If the user returns to the Web page, the applet container calls the applet s start method to instantiate and start three new threads. Performance Tip 15.5 Stopping applet threads when leaving a Web page is a polite programming practice because it prevents your applet from using processor time (which can reduce performance) on the browser s machine when the applet is not being viewed. The threads can be restarted from the applet s start method, which is invoked by the browser when the Web page is revisited by the user. 15.11 Thread Groups Sometimes it is useful to identify various threads as belonging to a thread group; class ThreadGroup contains methods for creating and manipulating thread groups. At constructor time, the group is given a unique name via a String argument. The threads in a thread group can be manipulated as a group. It may, for example, be desirable to interrupt all the threads in a group. A thread group can be the parent thread group to a child thread group. Method calls sent to a parent thread group are also sent to all the threads in that parent s child thread groups. Class ThreadGroup provides two constructors. The constructor public ThreadGroup( String stringName ) constructs a ThreadGroup with name stringName. The constructor public ThreadGroup( ThreadGroup parentThreadGroup, String stringName ) constructs a child ThreadGroupof parentThreadGroup called stringName. Class Thread provides three constructors that enable the programmer to instantiate a Thread and associate it with a ThreadGroup. The constructor public Thread( ThreadGroup threadGroup, String stringName ) constructs a Thread that belongs to threadGroup and has the name stringName. This constructor is normally invoked for derived classes of Thread whose objects should be associated with a ThreadGroup.
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Anonymous web server - Chapter 15 Multithreading 875 Fig. 15.17 Demonstrating the

Friday, September 14th, 2007

Chapter 15 Multithreading 875 Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 5 of 5). The whileloop at lines 129 179 continues to execute as long as the specified Thread reference is equal to the reference to the currently executing thread (currentThread). In each iteration of the loop, the thread sleeps for a random interval from 0 to 1 second. When the user clicks the JCheckBoxto the right of a particular JLabel, the corresponding Thread should be suspended (temporarily prevented from executing) or resumed (allowed to continue executing). In previous versions of Java, methods suspend and resumeof class Threadwere provided to suspend and resume a thread s execution. These methods are now deprecated (i.e., they should no longer be used) because they introduce the possibility of deadlock in a program if they are not used correctly. Suspending and resuming of a thread can be implemented using thread synchronization and methods wait and notify of class Object. Lines 137 147 define a synchronized block of code (also called a synchronized statement) that helps suspend the currently executing Thread. When the Threadreaches the synchronizedblock, the applet object (referenced with RandomCharacters.this) is locked and the while structure tests suspended[index]to determine if the Threadshould be suspended (i.e., true). If so, line 144 invokes method waiton the applet object to place the Threadin the waiting state. [Note the use of RandomCharacters.this to access the applet class s this reference from the private inner class RunnableObject.] When the Thread should resume, the program tells all waiting threads to become ready to execute (we will discuss this shortly). However, only the resumed thread will get a chance to execute. The other suspended thread(s) will reenter the waiting state. Lines 156 177 use SwingUtilities method invokeLater to update the JLabel for the appropriate thread. This example uses an anonymous inner class to implement the Runnableinterface (lines 161 175) and passes the anonymous inner class object to invokeLater. Lines 167 168 choose a random character from the alphabetstring. Lines 170 172 display the character on the appropriate JLabelobject. Software Engineering Observation 15.4 An inner class can reference its outer class s this reference by preceding the this reference with the outer class name and a dot operator. If the user clicks the Suspended check box next to a particular JLabel, the program invokes method actionPerformed (lines 93 111). The method determines which checkbox received the event. Using the index of that checkbox in array outputs, line 98 toggles the corresponding boolean in array suspended. Lines 101 102 set the background color of the JLabelto red if the thread is being suspended and green if the thread
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

874 Multithreading Chapter 15 139 while ( suspended[ (Web hosting uk)

Thursday, September 13th, 2007

874 Multithreading Chapter 15 139 while ( suspended[ index ] && 140 threads[ index ] == currentThread ) { 141 142 // Temporarily stop thread execution. Use 143 // applet as monitor. 144 RandomCharacters.this.wait(); 145 } 146 147 } // end synchronized block 148 } 149 150 // process InterruptedExceptions during sleep or wait 151 catch ( InterruptedException interruptedException ) { 152 System.err.println( “sleep interrupted” ); 153 } 154 155 // display character on corresponding label 156 SwingUtilities.invokeLater( 157 158 // anonymous inner class used by SwingUtilities 159 // method invokeLater to ensure GUI 160 // updates properly 161 new Runnable() { 162 163 // updates Swing GUI component 164 public void run() 165 { 166 // pick random character 167 char displayChar = alphabet.charAt( 168 ( int ) ( Math.random() * 26 ) ); 169 170 outputs[ index ].setText( 171 currentThread.getName() + “: ” + 172 displayChar ); 173 } 174 175 } // end anonymous inner class 176 177 ); // end call to SwingUtilities.invokeLater 178 179 } // end while 180 181 System.err.println( 182 currentThread.getName() + ” terminating” ); 183 } 184 185 } // end private inner class RunnableObject 186 187 } // end class RandomCharacters Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 4 of 5).
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Web design software - Chapter 15 Multithreading 873 87 // make all

Thursday, September 13th, 2007

Chapter 15 Multithreading 873 87 // make all waiting threads ready to execute, so they 88 // can terminate themselves 89 notifyAll(); 90 } 91 92 // handle button events 93 public synchronized void actionPerformed( ActionEvent event ) 94 { 95 for ( int count = 0; count < checkboxes.length; count++ ) { 96 97 if ( event.getSource() == checkboxes[ count ] ) { 98 suspended[ count ] = !suspended[ count ]; 99 100 // change label color on suspend/resume 101 outputs[ count ].setBackground( 102 !suspended[ count ] ? Color.green : Color.red ); 103 104 // if thread resumed, make sure it starts executing 105 if ( !suspended[ count ] ) 106 notifyAll(); 107 108 return; 109 } 110 } 111 } 112 113 // private inner class that implements Runnable so objects 114 // of this class can control threads 115 private class RunnableObject implements Runnable { 116 117 // Place random characters in GUI. Local variables 118 // currentThread and index are declared final so 119 // they can be used in an anonymous inner class. 120 public void run() 121 { 122 // get reference to executing thread 123 final Thread currentThread = Thread.currentThread(); 124 125 // determine thread's position in array 126 final int index = getIndex( currentThread ); 127 128 // loop condition determines when thread should stop 129 while ( threads[ index ] == currentThread ) { 130 131 // sleep from 0 to 1 second 132 try { 133 Thread.sleep( ( int ) ( Math.random() * 1000 ) ); 134 135 // Determine whether thread should suspend 136 // execution. Use applet as monitor. 137 synchronized( RandomCharacters.this ) { 138 Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 3 of 5).
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

872 Multithreading Chapter 15 35 (Yahoo web hosting) 36 // create

Wednesday, September 12th, 2007

872 Multithreading Chapter 15 35 36 // create GUI components, register listeners and attach 37 // components to content pane 38 for ( int count = 0; count < SIZE; count++ ) { 39 outputs[ count ] = new JLabel(); 40 outputs[ count ].setBackground( Color.green ); 41 outputs[ count ].setOpaque( true ); 42 container.add( outputs[ count ] ); 43 44 checkboxes[ count ] = new JCheckBox( "Suspended" ); 45 checkboxes[ count ].addActionListener( this ); 46 container.add( checkboxes[ count ] ); 47 } 48 } 49 50 // Create and start threads. This method called after init 51 // and when user revists Web page containing this applet 52 public void start() 53 { 54 // create threads and start every time start is called 55 for ( int count = 0; count < threads.length; count++ ) { 56 57 // create Thread and initialize it with object that 58 // implements Runnable 59 threads[ count ] = new Thread( new RunnableObject(), 60 "Thread " + ( count + 1 ) ); 61 62 // begin executing Thread 63 threads[ count ].start(); 64 } 65 } 66 67 // determine thread location in threads array 68 private int getIndex( Thread current ) 69 { 70 for ( int count = 0; count < threads.length; count++ ) 71 72 if ( current == threads[ count ] ) 73 return count; 74 75 return -1; 76 } 77 78 // called when user switches Web pages; stops all threads 79 public synchronized void stop() 80 { 81 // Indicate that each thread should terminate. Setting 82 // these references to null causes each thread's run 83 // method to complete execution. 84 for ( int count = 0; count < threads.length; count++ ) 85 threads[ count ] = null; 86 Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 2 of 5).
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

Web server logs - Chapter 15 Multithreading 871 The applet class RandomCharactersdisplays

Wednesday, September 12th, 2007

Chapter 15 Multithreading 871 The applet class RandomCharactersdisplays three JLabels and three JCheck- Boxes. A separate thread of execution is associated with each JLabel and button pair. Each thread randomly displays letters from the alphabet in its corresponding JLabel object. The applet defines the Stringalphabet(line 16) containing the letters from A to Z. This string is shared among the three threads. The applet s startmethod (lines 52 65) instantiates three Thread objects (lines 59 60) and initializes each with an instance of class RunnableObject, which implements interface Runnable. Line 63 invokes the Threadclass startmethod on each Thread, placing the threads in the ready state. Class RunnableObject is defined at lines 115 185. Its run method (line 120) defines two local variables. Line 123 uses static method currentThread of class Threadto determine the currently executing Threadobject. Line 125 calls the applet s utility method getIndex(defined at lines 68 76) to determine the index of the currently executing thread in the array threads. The current thread displays a random character in the JLabel object with the same indexin array outputs. 1 // Fig. 15.17: RandomCharacters.java 2 // Demonstrating the Runnable interface. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class RandomCharacters extends JApplet 12 implements ActionListener { 13 14 // declare variables used by applet and 15 // inner class RunnableObject 16 private String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”; 17 private final static int SIZE = 3; 18 19 private JLabel outputs[]; 20 private JCheckBox checkboxes[]; 21 22 private Thread threads[]; 23 private boolean suspended[]; 24 25 // set up GUI and arrays 26 public void init() 27 { 28 outputs = new JLabel[ SIZE ]; 29 checkboxes = new JCheckBox[ SIZE ]; 30 threads = new Thread[ SIZE ]; 31 suspended = new boolean[ SIZE ]; 32 33 Container container = getContentPane(); 34 container.setLayout( new GridLayout( SIZE, 2, 5, 5 ) ); Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 1 of 5).
Check Tomcat Web Hosting services for best quality webspace to host your web application.