Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

Say we have these two Runnables:

class R1 implements Runnable {

    public void run() { … }

    …

}

class R2 implements Runnable {

    public void run() { … }

    …

}

Then what's the difference between this:

public static void main() {

    R1 r1 = new R1();

    R2 r2 = new R2();

    r1.run();

    r2.run();

}

And this:

public static void main() {

    R1 r1 = new R1();

    R2 r2 = new R2();

    Thread t1 = new Thread(r1);

    Thread t2 = new Thread(r2);

    t1.start();

    t2.start();

}

1 Answer

0 votes
by (46k points)

First example: No various threads. Both execute in a single (existing) thread. No thread creation.

R1 r1 = new R1();

R2 r2 = new R2();

r1 and r2 are just two separate objects of classes that perform the Runnable interface and thus achieve the run() method. When you call r1.run() you are effecting it in the current thread.

Second example: Two separate threads.

Thread t1 = new Thread(r1);

Thread t2 = new Thread(r2);

t1 and t2 are recipients of the class Thread. When you call t1.start(), it begins a new thread and calls the run() order of r1 within to execute it within that new thread.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...