3

I've got some problems while learning threads in Java. The goal is to make a simulation that shows us how rabbits are running from wolves on some kind of board. Every wolf and every rabbit should be a thread. So I created a GUI in main method of Test class and created a new class that implements the Runnable interface. That's easy and logical I think. But now, how can I call the AddRabbit method from these threads? Because very thread should do mething like:

  1. Change its properties like place on the map
  2. Check other threads place on the map
  3. Paint itself on the panel

But how?

Lee Fogg
  • 775
  • 6
  • 22
ŁukaszG
  • 596
  • 1
  • 3
  • 16
  • You are using the wrong tool for your job. Thread should be used when you want to have *concurrent* execution which does not mean parallel (as often naïvely assumed) but rather *without any timing relationship*. A *simulation* on the other hand usually implies that all actors/ components shall perform their activities in relationship to each other which is the opposite. You should use plain objects and a `Timer`. – Holger May 13 '14 at 14:41

2 Answers2

5

Updating Swing components directly using multiple threads is not allowed--Swing is not threadsafe. There is a single Swing event queue that it processes, so if you have to update a JComponent in an existing thread, you will use the following code:

//You are currently in a separate thread that's calculating your rabbit positions
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        //Put in code to modify your Swing elements
    }
});

So every time you feel the need to update your GUI, then you can pass an instance of Runnable onto the Swing event queue using the SwingUtilities.invokeLater method, which it will process in its own thread.

shimizu
  • 998
  • 14
  • 20
  • Good, easy and nice answer but u didn't get the question or i wrote it no enough clearly. The goal is to operate on one object with few threads. Where do i need to create this object ? In Test class ? For now i have created it in Test class but i feel its not nice idea, and i dont know why ^^ Anyway thanks ! – ŁukaszG May 10 '14 at 20:28
  • This is a correct approach; a complete example is seen [here](http://stackoverflow.com/a/7519403/230513). – trashgod May 10 '14 at 20:52
4

A continuation, suggested here, is a good choice for updating the GUI from multiple threads, but it may be difficult to correctly synchronize access to shared data.

Alternatively, use a javax.swing.Timer to periodically update a model that manages the properties of wolves and rabbits. A related example of objects moving on a grid is examined here. For greater flexibility, use the Model–View–Controller pattern, illustrated here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045