Threads
Keywords
Thread, Runnable, synchronized, notify
Locking
The three rules from Doug Lea :
- Always lock during updates to object fields
- Always lock during access of possibly updated object fields
- Never lock when invoking methods on other objects
Curves
This example draw two curves in the same time using two threads. It is composed of two files : Curve.java and CurveApplication.java. Please note the use of an handle in the class Curve : the abstract method function(double x), and java2D for drawing curves.
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.
PingPong
Four examples of Ping and 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.java, Buffer.java.
A quite similar example with an infinite loop and different velocities : Consumer.java, Producer.java, TestProducerConsumer.java, Buffer.java.
Counter
A simple example about use of threads, composed with two classes : Counter.java and ButtonCounter.java. The method increase() in Counter illustrates the three Lea's rules :
- The increase of the data counter must be synchronized (rule 1).
- The following solution :
public synchronized void increase() {
button.setText(Integer.toString(counter++));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
is not correct because of the invocation of setText on the button (rule 3).
- The following solution :
public void increase() {
synchronized (this) {
counter++;
}
button.setText(Integer.toString(counter));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
is not correct because of the access to the data counter (rule 2).
Particle
This example demonstrates the three rules from Doug Lea. 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 like in the first version. Only ParticleFrame.java has been modified.