dtechlearn
dtechlearn

Reputation: 362

How to access class inside a thread

I am trying to do following in gui class for notifying registred observers.

public class GUI extends javax.swing.JFrame implements Observer {

public notImportantMethod() {

 t = new Thread() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                       myObject.registerObserver(this);   
                 }
            }

        };
        t.start();
      }
}

It gives me error: incompatible types: cannot be converted to Observer How can I use this? I know inside of run there is another context but how could I access it?

Upvotes: 1

Views: 1775

Answers (3)

Suraj Kumar
Suraj Kumar

Reputation: 109

@Ishnark has answered it correctly. You should be able to access it via GUI.this, that's all that you need to do.

Upvotes: -1

otoomey
otoomey

Reputation: 999

If you're looking for quick and dirty: (this is not good practice)

public notImportantMethod() {

final GUI self = this;

 t = new Thread() {
            @Override
            public void run() {
                for (int i = 1; i <= 10; i++) {
                       myObject.registerObserver(self);   
                 }
            }

        };
        t.start();
      }
}

Otherwise I would recommend looking up a tutorial on multi-threading and/or concurrency in java, like this one: http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/

Upvotes: 0

Ishnark
Ishnark

Reputation: 681

this now refers a Thread. You should be able to call GUI.this. For more info, see here .

Upvotes: 3

Related Questions