Jeremy
Jeremy

Reputation: 1

Parallel infinite loop

I'm using threads for the first time in Java. Let me know what here is causing an infinite loop and how I can resolve it. I think the issue is being caused by the fact that I'm using a GUI along with threading.

What happens is that infinite copies of the GUI pop up.

public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
                new RollplayGUI();
        }
    });
}

public RollplayGUI() {
    createGUI();
    RollplayGUI rg = new RollplayGUI();
    Thread trg = new Thread(rg);
    trg.setDaemon(true);
    trg.run();
}

public void run() {
        //Some fun stuff my daemon thread is supposed to do 
    }

The reason I'm doing this is that the run() method does some net code that blocks until it gets a connection from another program.

Upvotes: 0

Views: 352

Answers (5)

Jerry Saravia
Jerry Saravia

Reputation: 3837

One reason you get an infinite number of gui's is that you have each RollplayGUI creates a new RollplayGUI right after it is instantiated.

Additionally, you should call start() on Thread object, not run. If you call run then it's as if you're not doing threading. start() handles the threading properly.

Upvotes: 2

foxy
foxy

Reputation: 7672

When you create your first RollplayGUI, the constructor is called. Inside that constructor you create a new RollplayGUI, whose constructor will again call RollplayGUI. This will occur indefinitely, which is the infinite loop.

The line is

RollplayGUI rg = new RollplayGUI();

Upvotes: 0

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

What Justin said, but once that is fixed you're never starting your thread. You're just creating a Thread object (which will represent the thread when and if it starts) and then executing its run() method in the original thread. Use trg.start() instead of trg.run() to actually launch the thread.

Upvotes: 0

Spencer
Spencer

Reputation: 1496

This is an infinite loop because you have your RollbackGUI() create a new RollbackGUI(). Remove this line:

RollplayGUI rg = new RollplayGUI();

Upvotes: 0

Justin Beckwith
Justin Beckwith

Reputation: 7866

Your code is failing because the RollplayGUI constructor is instantiating a new RollplayGUI object. This will result in an infinite loop and likely a ... stack overflow.

Upvotes: 7

Related Questions