1

k, I am going through few Game Development Tutorials of Java, and I have to work with Threads and there is a "this" thing Thread thread = new Thread(this); that I am unable to understand, I am implementing my Class by "Runnable". What I think about it, is that "this" refers to Runnable to seek for the Run Method that I have defined in MY Class. And If I don't do this, It won't be looking for Run() Method here in my Class. Don't really know If M-Effed, but please correct me If I am wrong....

Waqas Ahmed
  • 45
  • 1
  • 1
  • 4

2 Answers2

2

this is a pseudo-variable that points to the current instance, to the object itself where the method is being executed. So for example:

public class Person {
    private String name;
    public void setName(pName) {
        this.name = pName
    }
}

Person p = new Person();
p.setName("Peter");

In the above code, we're assigning the new name "Peter"to this person p, the current instance of the class Person. In other words, from the point of view of p, this is pointing to p.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

@Óscar López explains what this means.

If your code contains this:

    Thread thread = new Thread(this);

then this refers to an instance of the class that contains that statement. Furthermore, it is the instance that is running the code. Furthermore, the API spec of that Thread constructors means that this needs to be an instance of a class that implements Runnable.

In short, your class needs to be declared as implements Runnable, and it needs to have a method with this signature:

    public void run() 
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216