Java, replacement for infinite loops?

前端 未结 9 726
花落未央
花落未央 2021-01-13 00:45

I am making a program that shows cellular growth through an array. I have gotten it so when I press the start button, the array updates every 10 seconds in a while(true){} l

相关标签:
9条回答
  • 2021-01-13 01:10

    I would suggest using a seperate thread to handle the array. Make sure you are using thread safe object (check Java Docs) and simply call .start() on your thread object when you want to start. Keep a pointer to it so you can pause it via setPaused(true)

    Something like this....

    class MyArrayUpdater extends Thread {
        private volatile boolean enabled = true;
        private volatile boolean paused = true;
    
        @Override
        public void run() {
            super.run();
            try {
                while (enabled) {
                    if (!paused) {
                        // Do stuff to your array here.....
                    }
                    Thread.sleep(1);
                }
            } catch (InterruptedException ex) {
                // handle ex
            }
        }
    
        public void setEnabled(boolean arg) {
            enabled = arg;
        }
    
        public void setPaused(boolean arg) {
            paused = arg;
        }
    }
    
    0 讨论(0)
  • 2021-01-13 01:12

    Another way to handle this problem is by using BlockingQueue of jobs.

    0 讨论(0)
  • 2021-01-13 01:20

    If those "buttons" are Swing buttons, then the way to do this is: have the Start button create a new javax.swing.Timer object which does the update every 10 seconds. Then have the Pause button stop that timer.

    0 讨论(0)
  • 2021-01-13 01:21

    What you're looking for is multi-threading. Take the data processing and put it in a second thread, run it asynchronously, and use the main thread to check for user input.

    Of course this might also entail using a semaphore to communicate between the two threads. What level class are you in - have you covered both of these topics already?

    0 讨论(0)
  • 2021-01-13 01:24

    Yep. Sounds like you're doing your drawing on the event dispatcher thread. Events (button presses) never have a chance to get called because you've never returned control from the last time it was called...

    0 讨论(0)
  • 2021-01-13 01:28

    You want to run your simulation in a Thread ( Look for Runnable Interface ). Then you can pass messages to this Thread to pause, continue and stop.

    0 讨论(0)
提交回复
热议问题