Where is the link in this thread?

I want to start learning Java a bit. I am going to write a fairly basic program in which I want to show a series of numbers (1,2,3,4, 5 .... etc) in an infinite loop. The program should exit if someone hits a specific key (Say ESCAPE key). So I thought about using Threads for these two tasks (endless loop and user binding). I just have a thread for an infinite loop, and here is what 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();
    }

}

, , "this" . - , . , . , , , , . - , "this" :

counter = new Thread(this);
+4
2

, Runnable? new Thread(this), : " , "

Thread, , Runnable.

+5

., , ...

... , , , , . , , .

, Java- :

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

, Runnable. , LearnJava.start(), LearnJava : run().

+3

Source: https://habr.com/ru/post/1539018/


All Articles