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 <= greetingCount)
{
if (!queue.isFull())
{
queue.add(i + ": " + greeting);
i++;
}
Thread.sleep((int)(Math.random() * DELAY));
}

Consumer Thread

int i = 1; 
while (i <= greetingCount)
{
if (!queue.isEmpty())
{
Object greeting = queue.remove();
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

.

Locks

Reentrant Locks

aLock = new ReentrantLock();
. . .
aLock.lock();
try
{
protected code
}
finally
{
aLock.unlock();
}

Scenario with Locks

  1. First thread calls add and acquires lock, then executes
    elements[tail] = anObject;
  2. Second thread calls add and tries to acquire lock, but it is blocked
  3. First thread executes
    tail++;
  4. First thread completes add, releases lock
  5. Second thread unblocked
  6. Second thread acquires lock, starts executing protected code

Deadlocks

Avoiding Deadlocks

Avoiding Deadlocks

Object Locks

Object Locks

Visualizing Locks

Visualizing Locks

.

Algorithm Animation

Algorithm Animation


Pausing and Running the Animation