4

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);
BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70

2 Answers2

5

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.

Matthew G.
  • 1,298
  • 10
  • 24
3

Nothing wrong with Matthew G.'s answer, but taking it a little bit further...

...A program with many classes that each have just one responsibility usually is better than a program with one class that has many responsibilities. I know you are just beginning the learn the language, but it's not too early to start learning good habits.

Here's a pattern that you will see often in other people's java code:

Thread fooThread = new Thread(new Runnable(){
    @Override
    public void run() {
        ...do something interesting here...
    }
});

This creates a new instance of an anonymous class that implements the Runnable interface. It may not look like much, but if you used it in your LearnJava.start() method, then there would be one less responsibility for your LearnJava class: It would not have to implement a run() method.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57