CIS 260 Multithreading - the problem

A process is a self-contained running program with its own address space. A thread is a single sequential flow of control within a process. Switching processes is very expensive compared to switching threads. Having threads is similar to having multiple programs running simultaneously. Why do we want threads?

Every program in Java is multithreaded. The garbage collector runs independently of the rest of your application. Every program you write executes in a thread automatically. GUI interfaces can become unusable without multiple threads. Perhaps an example is best.

This first example is a simple GUI which demonstrates the need for multiple threads. Once the start button is pushed, its routine hogs the processor and the GUI becomes unresponsive.

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

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

   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {
         public void run() {
            TThread0 app = new TThread0();
            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 < 10000) {
         // 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));
      }
   }
}

Previous: multithreading

Next: sleep