Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the reference in this Thread going ?

I want to start learning Java a bit. I am about to write a pretty basic program, where I want to display a series of numbers (1,2,3,4, 5….etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key). So I thought about using Threads for those two tasks (infinite loop and the user binding). I just have a Thread for the infinite loop and this is how my Code looks like:

public class LearnJava implements Runnable {

    private int i = 0;
    private boolean running = false;
    private Thread counter;

    public void start(){
        running = true;
        counter = new Thread(this);
        counter.start();
    }

    /*the stop method is not really in use yet*/
    public void stop(){
        running = false;
        try{
            counter.join();
        } 
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public void run(){
        while (running){
            System.out.println("ThreadTest: " + i);
            i++;        
        }

    }

    public LearnJava(){
    }

    public static void main(String[] args){
        LearnJava programm = new LearnJava();
        programm.start();
    }

}

Now what I don't understand in my own example is the "this" reference in my Thread. I always tried to run it with out any reference, because I didn't knew the reason for it. I just got the correct code by random to be honest. I wrote it all by myself and thought to understand it properly but obviously I am not. Can anybody explain why I needed to take the "this" reference in line:

counter = new Thread(this);
like image 548
BoJack Horseman Avatar asked Feb 13 '23 02:02

BoJack Horseman


1 Answers

Notice that you've implemented the Runnable interface? When you say new Thread(this) you're saying "Create a new Thread which will run my class when started"

Take a peek at the documentation for Thread, and you'll see a constructor which takes a Runnable.

like image 58
Matthew G. Avatar answered Mar 07 '23 01:03

Matthew G.