There is a class for the stream, the code from the cash register constructor always works, and run () is run once, what could be the reason? The log is empty.

public class SThread extends Thread { Thread ScoreThread; public SThread() { ScoreThread = new Thread(this); ScoreThread.start(); } public void run() { while(running) { if(!onDraw)return; try{Thread.sleep(500);}catch (InterruptedException e){e.printStackTrace();} score++; text = "Score: "+score; } } } 

I call like this

 new SThread(); 

    1 answer 1

    Starting a thread in the constructor and passing this , you pass a reference to an object that is not yet fully constructed. The thread starts earlier than the constructor is completed, so the result is not predictable. Plus in your case it is better to use Runnable .

     public class SThread implements Runnable{ Thread ScoreThread; public SThread(){ ScoreThread = new Thread(this); } public void start() { ScoreThread.start(); } public void run(){ while(running){ if(!onDraw)return; try{Thread.sleep(500);}catch (InterruptedException e){e.printStackTrace();} score++; text = "Score: "+score; } } } 

    And run:

      SThread thread = new SThread (); thread.start();