Concurrent Programming with Java Threads



General Information

Static methods of Integer, Double, Math, and System. Important IO idioms.

Introduction

A thread of control is a path taken by a program during execution. A parallel program has multiple threads of control. Each thread is executed in order but the relative order of execution of statements in different threads of control is unknown. In fact, they could be executed concurrently (if the computer has multiple processors and the JVM supports this).

Why? Non-blocking I/O, alarms and timers, GUI programming.

Multiple threads of control influence the design of the language (e.g, synchronized keyword), but to the programmer the basic functionality in encapsulated in the class structure like ordinary libraries.

The central class is the Java class The principle methods are:

Books: Java Threads by Scott Oakes and Henry Wong. Concurrent Programming in Java: Design Principles and Patterns by Doug Lea.

Thread Creation

There are two equivalent ways of forking threads.
  1. Extend Thread as in Simple.java

  2. Implements Runnable as in SimpleRun.java

    Notice the use of Thread.currentThread().

thread life cycle Life cycle of a thread

Passing Information, Priority, Deamon

Uncaught exceptions in threads ...

Update Anomalies and Synchronization

Every object has a lock. (Also every class has Class object, so even classes have locks. This is the lock used by static methods.)
synchronized (o) {  // block on object's "lock" until the current
                    // thread gains exclusive control of it.
   // critical region
}

wait/notify

The classic consumer/producer problem:

wait() and notify() methods of Object. They apply to particular object, just as locks do. wait() and notify() must be in a synchronized block. Wait atomically releases the lock and suspends.

Two Phase Locking

Concurrency Utilities

Like the "Collection Framework" the new package of "Concurrency Utilities" is designed to provide the most common infrastructure for concurrent applications.

Miscellaneous

Example

The following is an example of using threads to avoid blocking on IO. The following program executes an arbitrary command by appealing to the OS. The command may require input and may produce output. Different commands may do these requests in different order and may block. For example, if the Java program fails to give the program input because it is waiting on the program to produce output, deadlock may result.
Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Tue Sep 29 09:26:35 EDT 2009