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
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.java, Buffer.java.
A fairly similar example with an infinite loop and different
velocities : Consumer.java,
Producer.java,
TestProducerConsumer.java, Buffer.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 :
- 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).
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.