Threads

The Java Tutorial on threads

Keywords

Thread, Runnable, synchronizednotify

Locking

The three rules from Doug Lea :
  1. Always lock during updates to object fields
  2. Always lock during access of possibly updated object fields
  3. Never lock when invoking methods on other objects

PingPong

Four examples of Ping-Pong  : PingPong1.java et PingPong1b.java (Thread vs. Runnable), PingPong2.java et PingPong3.java (using synchronized).

Producer / Consumer

An example of producer/consumer between several threads with a shared buffer : Consumer.java, Producer.java, TestProducerConsumer.javaBuffer.java.
A fairly similar example with an infinite loop and different velocities : Consumer.java, Producer.java, TestProducerConsumer.javaBuffer.java.

Curves

This example draws two curves at the same time using two threads. It is composed of two files : Curve.java and CurveApplication.java. Please note the use of a handle in the class Curve : the abstract method function(double x), and java2D for drawing curves.
Same exemple, but using lambda expressions instead of an handle : Curve.java, CurveApplication.java and Function.java.
A second version, more sophisticated,  TestMemory.java, uses a shared memory: Memory.java between a reading thread Reading.java and a writing thread Acquirement.java.

Counter

A simple example about the use of threads, composed of two classes : Counter.java and ButtonCounter.java. The method increase() in Counter illustrates Lea's three rules :

Particles

This example demonstrates Doug Lea's three rules. It is composed of three files : ParticleFrame.java, Particle.java and ParticleComponent.java.
In a second version, the moves of the particles are simply interrupted and not initialized again as in the first version. Only ParticleFrame.java has been modified.