Object-Oriented Design & Patterns

Cay S. Horstmann

Chapter 9

Multithreading

   

Chapter Topics

Threads

Running Threads

Running Threads

public class MyRunnable implements Runnable
{
public void run()
{
thread action
}
}
...
Runnable r = new MyRunnable();
Thread t = new Thread(t);
t.start();

Thread Example

Thread Example

.

Thread Example

1: Hello, World! 
1: Goodbye, World!
2: Hello, World!
2: Goodbye, World!
3: Hello, World!
3: Goodbye, World!
4: Hello, World!
4: Goodbye, World!
5: Hello, World!
5: Goodbye, World!
6: Hello, World!
6: Goodbye, World!
7: Hello, World!
7: Goodbye, World!
8: Goodbye, World!
8: Hello, World!
9: Goodbye, World!
9: Hello, World!
10: Goodbye, World!
10: Hello, World!

Starting Two Threads

.

Thread States

Thread States

.

Blocked Thread State

Scheduling Threads

Terminating Threads

Sensing Interruptions

Sensing Interruptions

public class MyRunnable implements Runnable
{
public void run()
{
try
{
while (...)
{
do work
Thread.sleep(...);
}
}
catch (InterruptedException e) {}
clean up 
}
}

Thread Synchronization

Producer Thread

int i = 1; 
while (i <= repetitions)
{
if (!queue.isFull())
{
queue.add(i + ": " + greeting); i++;
}
Thread.sleep((int)(Math.random() * DELAY));
}

Consumer Thread

int i = 1; 
while (i <= repetitions)
{
if (!queue.isEmpty())
{
Object greeting = queue.removeFirst();
System.out.println(greeting);
i++;
}
Thread.sleep((int)(Math.random() * DELAY));
}

Expected Program Output

1: Hello, World! 
1: Goodbye, World!
2: Hello, World!
3: Hello, World!
...
99: Goodbye, World!
100: Goodbye, World!

Why is Output Corrupted?

Race Condition Scenario

Race Condition Scenario

.

Object Locks

Scenario with Synchronized Methods

Visualizing Locks

Visualizing Locks

.

Deadlocks

Deadlocks

Avoiding Deadlocks

Avoiding Deadlocks

Algorithm Animation

Algorithm Animation

.

Algorithm Animation

Pausing and Running the Animation

Gate

Gate

.

Pausing and Running the Animation

Animation Classes

.