0

I have written a small sample code:

public class Button2 implements Runnable{    
    JButton jButton = new JButton();
    static boolean changeContext = false;    
    public Button2(){
        jButton.setText("ButtonTWO");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeContext = true;
                ((JButton)e.getSource()).setEnabled(false);
            }
        });
    }
    @Override
    public void run() {
        System.out.println("ButtonTWO run...");
        jButton.setEnabled(true);
        while(true){
            if(changeContext)
                break;
        }
        changeContext = false;        
    }
}

When I run it like:

Button2 threadTWO = new Button2();
Thread thread2;
            try{
                thread2 = new Thread(threadTWO);
            thread2.start();
            thread2.join();
            }catch(Exception ex){
                System.out.println("Ëxception caught");
            }

It never comes out, even after clicking button.

If I add a sysout or Thread.sleep(1) after while(true) in run method, it comes out of while loop. What can be the possible reason?

Swaraj Shekhar
  • 187
  • 1
  • 7
  • 28

1 Answers1

0

I assume you're running the bottom portion on the EDT. Thus you're creating the button (and hopefully add it to your ui somehow) then start the thread and make the EDT wait for the thread to die (thread2.join()), hence the EDT can't process the events and changeContext = true is never called.

That adding something makes the loop end probably is due to missing braces:

This only ends the loop if changeContext is true:

if(changeContext)
   break;

I assume you did this:

if(changeContext)
   Thread.sleep(1);
   break;

The above calls sleep if changeContext is true and then immediately ends the loop (the break is not inside the if-block anymore. So if you want consistent behavior write it like this:

if(changeContext) {
   Thread.sleep(1);
   break;
}

Btw, Apple had a security issue last year which basically had a similar source (a double break and no braces).

Thomas
  • 87,414
  • 12
  • 119
  • 157