Jan Gimmler
Jan Gimmler

Reputation: 43

Java Thread not executing

I'm trying to create a thread in Java and it's looks like it would work (thread is starting and if I try to write some random thinks into the code, the programm will return errors in thread-0. But for some reason, the code in the Thread is just not executing. When I put a simple system.out.printl on the beginning, it's not showing. I didn't found anything when I searched for this problem, so I hope you can help me.

Main:

  public class Main {
        public static void main(String[] args) throws java.io.IOException{

            SendMessages sm = new SendMessages();
            sm.start();

            System.out.println("2");

            while(true){
            }
        }
 }

Thread:

public class SendMessages extends Thread {
    public void run(String[] args) throws java.io.IOException {

        System.out.println("1");
    }   
}

The "2" is printing, but not the "1".

Greetings

Upvotes: 1

Views: 88

Answers (2)

Mshnik
Mshnik

Reputation: 7032

You're not overriding the run() method correctly. The correct method signature for run is: public void run(), with no params. If you change your SendMessages class to

public class SendMessages extends Thread {
    @Override
    public void run() {
        System.out.println("1");
    }   
}

You should see the 1 printed. This is why the @Override annotation is useful - it tells you when the method you've written isn't actually overriding anything.

Upvotes: 1

Mik378
Mik378

Reputation: 22171

rundoes not throw exceptions and doesn't take parameters.

You have to override the good one:

public void run() {
}

You can add the @Override annotation to be sure that you override the good one:

@Override
public void run() {
}

Upvotes: 3

Related Questions