Threads

Basic Idea

Threads vs Processes

Multiple processes / tasks

Threads

Cooperative vs Pre-emptive

Cooperative multithreading

Pre-emptive

Operating system may choose

Example - Long action

Problem

The user presses a button on the GUI interface that starts a long action. The single GUI thread is now in use, so the GUI interface becomes completely unresponsive until the action is completed.

Solution

For long actions, start a separate thread so that the GUI thread may continue to operate the interface.

Example - Slow IO

Problem

IO is relatively slow. Let's say you're writing a browser. It reads a web page that has a lot of links to images. If you get the images sequentially, the program will spend most of its time waiting for network IO operations to complete.

Solution

Start a separate thread for each image that must be loaded. The IO wait time is therefore reduced to the longest wait, not the sum of all waits.

Example - Animation

Problem

You want to show an animated image, but also continue regular processing. Every so many milliseconds you need to draw a new image. How can you do this while you are doing some other computation?

Solution

Start a separate thread for the animation that starts up at regular intervals. The javax.swing.Timer class is a class that helps you do this.

Thread Life Cycle States

Thread Life Cycle Transition State Diagram

[ INSERT DIAGRAM HERE ]

Thread Scheduling

Thread class and Runnable Interface

Synchronization

Data Structures and Synchronization

Daemon Threads

Thread Methods

Thread Example

Object Methods for Threads

Timers

GUI and Threads

Separate Thread for Long Actions

GUI Listener Example

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
Thread   m_busyBee     = new WorkerBee();
Runnable m_showResults = new ResultsDisplayer();
JButton  m_gatherBtn   = new JButton("Gather Honey");
         m_gatherBtn.addActionListener(new BeeListener());
. . .
class ResultsDisplayer implements Runnable {
    public void run() {
        showWorkResults();
    }
}

class WorkerBee extends Thread {
    public void run() {
        gatherHoney();
        SwingUtilities.invokeLater(m_showResults);
    }
}

class BeeListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        disableControlsEnableCancel();
        m_busyBee.start();
    }
}

Thread pools

Updates to make

End