varmashrivastava
varmashrivastava

Reputation: 442

What will happen if we do entire Thread functionality in start method instead of run method?

What will happen if we do entire Thread functionality in start method instead of run method?Below code runs in same way as it would have run if I added code in run method..

   public class RunMethodTest extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Abc abc=new Abc();
        abc.start();
    }
}

class Abc extends Thread
{
    @Override
    public synchronized void start() {
        super.start();
        for(int i=0;i<10;i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread" + " " + i);
        }
    }
}

Upvotes: 1

Views: 50

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Test it: have your code tell you which thread it is being called in by

  1. Getting the current thread via Thread.currentThread()
  2. And then getting the current thread's id and name via getId() and getName()

public class ThreadTest {
    public static void main(String[] args) {
        Thread currentThread = Thread.currentThread();
        System.out.printf("Main, Which Thread: %s, %d%n", 
                currentThread.getName(), 
                currentThread.getId());

        Abc abc = new Abc();
        abc.start();
    }
}

class Abc extends Thread {
    @Override
    public synchronized void start() {
        super.start();

        Thread currentThread = Thread.currentThread();
        System.out.printf("Start, Which Thread: %s, %d%n", 
                currentThread.getName(), 
                currentThread.getId());

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread" + " " + i);
        }
    }

    @Override
    public void run() {
        super.run();

        Thread currentThread = Thread.currentThread();
        System.out.printf("Run, Which Thread: %s, %d%n", 
                currentThread.getName(), 
                currentThread.getId());
    }
}

For me this returns:

Main, Which Thread: main, 1
Start, Which Thread: main, 1
Run, Which Thread: Thread-0, 9
Thread 0
Thread 1
Thread 2
Thread 3
....

Which proves that your Abc's start method is (as expected) being called in the same thread as the calling code and not in a new thread, and that only code within the run() method is being called within a new thread. As has been noted above though, you almost never need to or want to extend Thread but rather implement Runnable or Callable.

Upvotes: 1

Related Questions