Search code examples
javamultithreadingswingwhile-loopthread-sleep

Java: Run multiple while loops at the same time


I'm trying to make several JRadioButtons blink at the same time with this blink method:

private void blink(JRadioButton button, boolean blinking)
{
    if(blinking)
    {
        while(true)
        {   
            try 
            {
                button.setSelected(true);
                Thread.sleep(500);
                button.setSelected(false);
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
    else
    {
        button.setSelected(false);
    }
}

I know it has something to do with threads but I'm not that familiar with them.


Solution

  • I'm trying to make several JRadioButtons blink at the same time with this blink method

    IMHO you don't need multiple while loops.

    Just add all buttons you want to blink to an ArrayList, then in the same while loop, loop over that list and blink the buttons. So, instead of

    button.setSelected(true);
    Thread.sleep(500);
    button.setSelected(false);
    Thread.sleep(500);
    

    You can use

    for(int i=0; i<yourList.size(); i++) {
        yourList.get(i).setSelected(true);
    }
    Thread.sleep(500);
    for(int i=0; i<yourList.size(); i++) {
        yourList.get(i).setSelected(false);
    }
    Thread.sleep(500);
    

    But this is a bad practice. Use the Timer class and schedule a thread to execute every 500ms instead:

    Timer t = new Timer(500, new ActionListener() {
        boolean selected = false; 
    
        @Override
        public void actionPerformed(ActionEvent e) {
            selected = !selected;
            for(int i=0; i<yourList.size(); i++) {
                yourList.get(i).setSelected(selected);
            }
        }
    });
    t.start();