I recently noted that several students in a beginning computer science class at my school had been learning event-driven programming by themselves, without bothering to use google or any textbooks. While I approve of this experimental learning approach in general, in this case, the result was less than good.
The programmers in question wanted to design a system in which, so long as the number of button presses was less than the number of lines in a certain file, pressing the button would retrieve the next line, process it, and print out the result. They did this as follows (I’ve made some modifications for readability):
- button.addActionListener(new MyActionListener());
- Scanner s=new Scanner(new File("values.txt"));
- while(s.hasNextLine()) {
- while(!button_pressed);
- button_pressed=false;
- processLine(s.nextLine());
- }
- private class MyActionListener implements ActionListener {
- public void actionPerformed(ActionEvent e) {
- button_pressed=true;
- }
- }
From the programmer’s standpoint, I suppose this actually is the intuitive way to do it. If the user wasn’t involved, we would just loop until there were no more lines, but since the user is involved, we have to wait for the user to press the button, hence the while loop. Nevertheless, this is a Very Bad way to do it. While in the loop on line 5, we are using 100% CPU, even though all we are doing is waiting. If we want to do another operation at the same time, we are doomed.
Read the rest of this entry »