Search code examples
javamultithreadingrunnableocpjp

Can you please explain this Thread working?


Heres the code about threads.....I dont know the difference between those 2 new() statements.

  Runnable r=new Runnable() {
    public void run() {
    System.out.print("Cat");
    }
    };

    Thread t=new Thread(r) {
    public void run() {
    System.out.println("Dog");
    }
    };
    t.start();

Output is Dog But why and how ?


Solution

  • Because you override Thread#run(), so this method is eventually executed when you start the thread. The default Thread#run() delegates to the passed-in Runnable. Rule of thumb: Either provide a Runnable or override Thread#run(), but don't do both!