0

I was learning to use multi-threading by using the Runnable interface.

This is how i am trying to do it

public class ExampleClass implements Runnable {


public static void main(String[] args) 
    { 
           Thread object = new Thread(new ExampleClass()); 
           object.start(); 
    } 
public void run(String[] args){
System.out.println("ExampleClass running");
   } 
}

However this doesn't work because my assumption is that the start method calls run() however since i have that method as run(String) in my example above, it doesn't work. The program compiles but then just exits.

Please can you advise what am I doing wrong?

user3423407
  • 341
  • 3
  • 13
  • 1
    The program compiles? It doesn't say that it's missing a no-arg `run()` method? – Kayaman Mar 27 '20 at 13:29
  • It's really weird that it compiles for you. I'm getting this error while trying to compile it: com.company.ExampleClass is not abstract and does not override abstract method run() in java.lang.Runnable – Amongalen Mar 27 '20 at 13:30
  • @Amongalen - you need to add unimplemented methods, you should see the suggestion next to the compilation error – user3423407 Mar 27 '20 at 18:14

1 Answers1

2

You can pass the arguments in the constructor of ExampleClass.

public class ExampleClass implements Runnable {

    private String[] args;

    public ExampleClass(String[] args) {
        this.args = args;
    }

    public static void main(String[] args) {
        Thread object = new Thread(new ExampleClass(args));
        object.start();
    }

    @Override
    public void run() {
        System.out.println("ExampleClass running, args: " + Arrays.toString(args));
    }
}
Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16