CIS 260 Multithreading - sleep

This example shows how the sleep() method can be used to try to solve the problem. In some languages this might work, but it sure doesn't work in this case. What we would hope for is that the rest of the program can have a turn while the doCount() routine is sleeping. But that's not what happens. The rest of the program still waits for doCount(), but now doCount() takes a lot longer to execute. The only effect is that the program now runs a lot slower.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class TThread1 extends JFrame {
   JButton btnStart, btnClear;
   JLabel lblNum;
   int count = 0;

   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            TThread1 app = new TThread1();
            app.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                  System.exit(0);
               }
            });
            app.init();
            app.pack();
            app.setVisible(true);
         }
      });
   }

   public void init() {
      Container c = this.getContentPane();
      c.setLayout(new GridLayout(3,1));
      lblNum = new JLabel("Running Total");
      btnStart = new JButton("Start");
      btnClear = new JButton("Clear");
      btnClear.setEnabled(false);

      btnStart.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            btnStart.setEnabled(false);
            btnClear.setEnabled(true);
            doCount();   
         }
      });

      btnClear.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            count = 0;
            lblNum.setText(Integer.toString(count++));
            btnStart.setEnabled(true);
            btnClear.setEnabled(false);
         }
      });

      c.add(lblNum);
      c.add(btnStart);
      c.add(btnClear);
   }

   private void doCount() {
      while (count < 100) {
         // next line not reflected until end
         lblNum.setText(Integer.toString(count++));
         // the following line is used to show activity
         System.out.println(Integer.toString(count));
         // attempting to correct problem with sleep()
         try {
            Thread.sleep(100);
         } catch (InterruptedException e) {
            System.out.println("Application Interrupted");
         }
      }
   }
}

Previous: the problem

Next: creating threads