Java Reference
In-Depth Information
public static final JList<String> COMPONENT = new JList<>();
public class CountingTask implements Runnable {
public void run() {
for (int i = 1; i <= LENGTH; i++) {
// Add an item
((DefaultListModel<String>) COMPONENT.getModel()).clear();
((DefaultListModel<String>)
COMPONENT.getModel()).addElement("At: "+i);
// Force component repaint
COMPONENT.repaint();
COMPONENT.invalidate();
COMPONENT.repaint();
// Sleep for a little to give other threads a chance
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public MultiThreadedFrame() {
DefaultListModel<String> listModel = new DefaultListModel<>();
COMPONENT.setModel(listModel);
getContentPane().add(COMPONENT);
pack();
setSize(300,500);
setVisible(true);
// Increase the number of threads if problem does not appear
for (int t = 0; t < 16; t++) {
Thread thread = new Thread(new CountingTask());
thread.start();
}
}
public static void main(String[] args) {
new MultiThreadedFrame();
}
}
When you run this code, you'll see a number of exceptions appearing in the console. Another unde-
sired aspect of the code is that you'll (most likely) end up with multiple elements in your JList when
the program stops running, even though you execute the clear() method before adding a new item
in every thread. This is due to the fact that threads can run in parallel, meaning that two threads
can add items right after they have both cleared the list.
Note Some Swing components' methods are called “thread safe.” However,
this behavior has changed between Java versions before, so it is generally a
good idea not to rely on thread-safe components. This also applies to JList .
Search WWH ::




Custom Search