Threads always preserve class invariants when they are allowed to exit normally, as long as the specification is followed. Programmers often try to forcefully terminate threads when they believe that the task is accomplished, the request has been canceled or the program or JVM needs to quickly shutdown.
...
This noncompliant code example shows a thread that fills a vector with pseudorandom numbers. The thread is forcefully stopped after a fixed amount of time.
Code Block | ||
---|---|---|
| ||
public final class Container implements Runnable {
private final Vector<Integer> vector = new Vector<Integer>(1000);
public Vector<Integer> getVector() {
return vector;
}
public synchronized void run() {
Random number = new Random(123L);
int i = vector.capacity();
while (i > 0) {
vector.add(number.nextInt(100));
i--;
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Container());
thread.start();
Thread.sleep(5000);
thread.stop();
}
}
|
...
Code Block | ||
---|---|---|
| ||
public final class Container implements Runnable {
private final Vector<Integer> vector = new Vector<Integer>(1000);
private volatile boolean done = false;
public Vector<Integer> getVector() {
return vector;
}
public void shutdown() {
done = true;
}
public synchronized void run() {
Random number = new Random(123L);
int i = vector.capacity();
while (!done && i > 0) {
vector.add(number.nextInt(100));
i--;
}
}
public static void main(String[] args) throws InterruptedException {
Container container = new Container();
Thread thread = new Thread(container);
thread.start();
Thread.sleep(5000);
container.shutdown();
}
}
|
...