-2

I don't understand what this keyword reference in this example:

public class Game extends Canvas implements Runnable{

    /* some code.. */
   
    private Thread thread;
    private boolean running=false;

    private synchronized void start(){
        if(running) return;
        running = true;
        thread = new Thread(this,"Thread");
        thread.start();
    }

}

First, I thought it could be written as : thread = new Thread(new Game(),"Thread"); but it doesn't work.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • as mentioned check the previous answers [check this](https://stackoverflow.com/questions/8708216/use-of-this-keyword-in-java/25807978)( – Giriteja Bille Jan 14 '21 at 10:14

1 Answers1

0

'this' always referrs to the current object. If you are inside a non-static method, 'this' is the reference you can use to access the object in which the method is run. (Sorry for the bad wording). In your case, 'this' is an instance of Game, and since Game implements Runnable it can be passed to the thread's constructor. I assume new Game() doesn't work because the game has the default running=false value.