When you want to schedule something to happen at regular intervals, you can use a java.util.Timer
with one or more java.util.TimerTask
s.
But whether you use timers or implement your own time scheduling with your own threads, you need some way to communicate from your Threads/TimerTasks with the objects in your main thread. You can implement this by passing these objects to these threads and then call methods on them in your run-method. But keep in mind that you have no control over what the main thread is doing when that method is called from the sub-thread. It might happen from time to time that the sub-thread changes a value while the main-thread is currently performing some operation with it. This can lead to strange bugs commonly referred to as race conditions. Take this example:
class ValueList {
private List<Integer> values = new ArrayList<>();
// this method may be called from many different threads to add values
public void add(Integer i) {
values.add(i);
}
// this method is called from the main thread to update the GUI
public int getAverage() {
int sum = 0;
for (Integer i: values) {
sum += i;
}
// Imagine a thread calls add(Integer) when the main threads
// execution is exactly here!
// the average will be too low because the new value was
// not yet counted for the sum, but is now accounted for
// when calculating the average from the sum.
return sum / values.size();
}
}
To prevent this from happening, familiarize yourself with the various synchronization features offered by Java.