Chapter a

Multithreading


Chapter Goals

Threads

Steps to Running a Threads

GreetingThread Outline

A program to print a time stamp and "Hello World" once a second for ten seconds
public class GreetingThread extends Thread
{
   public void run()
   {
      //thread action
      . . .
   }
   //variables used by the thread action
   . . .
}

Thread Action for GreetingThread

GreetingThread

GreetingThread run method

public run()
{
   try
   {
      //thread action
   )
   catch (InterruptedException exception)
   {
      //cleanup, if necessary
   }
}

File GreetingThread.java

To Start the Thread

File GreetingThreadTest.java

Thread Scheduler

Terminating Threads

Terminating Threads

 

Terminating a Thread

public void run(
{
   try
   {
      for (int = 1;
           i <= REPETITIONS && !isInterrupted();
           i++)
      {
         //do the work
      }
   }
   catch (InterruptedException exception)
   {
   }
   //cleanup
}

Corrupting Data with Unsynchronized Threads

 

run Method of DepositThread

public void run()
{
   try
   {
      for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++)
      {
         account.deposit(amount);
         sleep(DELAY);
       }
    }
    catch (InterruptedException exception)
    {
    }
 }

 

Sample Application

Scenario to Explain Non-zero Result

Scenario to Explain Non-zero Result

Race condition

Corrupting the Contents of the balance Field

Corrupting the Contents of the balance Field

File BankAccountThreadTest.java

File DepositThread.java

File WithdrawThread.java

File BankAccount.java

Solving the Race Condition Problem

 

Synchronized Methods

public class BankAccount
{
   public synchronized void deposit(double amount)
   {
      . . .
   }

   public synchronized void withdraw(double amount)
   {
      . . .
   }
   . . .
}

Synchronized Methods

Synchronized Methods

Visualization of Synchronized Thread Behavior

Deadlock

Deadlock

Avoiding Deadlock

 

withdraw Method to Avoid Deadlock

public synchronized void withdraw(double amount)
   throws InterruptedException
{
   while (balance < amount)
      wait();
}

Wait and NotifyAll

 

Restroom wait/notifyAll Analogy

File BankAccountThreadTest.java

Using synchronized methods

File BankAccount.java

Animation

Algorithm Animation

Selection Sort Algorithm Animation

Selection Sort Algorithm Animation

Selection Sort Algorithm Animation

Selection Sort Algorithm Animation

Selection Sort Algorithm Animation

Applet to Provide User Interface

Applet to Provide User Interface

Applet to Provide User Interface

Applet to Provide User Interface

A Step in the Animation of the Selection Sort Algorithm

Step in the Animation of the Selection Sort Algorithm

File SelectionSortApplet.java

File SelectionSorter