-5

I am calling start first and then run. When I run first run() then start(), run is being treated as a method and completely runs and then start is called, but in this way I am having the output as:

0Thread-1
0Thread-0
1Thread-1
1Thread-0
2Thread-0
2Thread-1
3Thread-1
3Thread-0
4Thread-1
4Thread-0

Why, once run is called, doesn't it completely run?

public class basic extends Thread {
  public void run (){
    for(int i = 0; i < 5; i++) {
      try {
        Thread.sleep(100);
        System.out.println(i+ this.getName());
      } catch (InterruptedException e) {
        System.out.println(e);
      }
    }
  }

  public static void main(String[] args) {
    basic x= new basic();
    basic y=new basic();
    x.start();
    y.run();
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KS HARSHA
  • 67
  • 2
  • 7
  • 2
    Well, i is not *like* 2 different threads being executed. It **is** 2 different threads being executed. The current thread, executing the run() method, and the started thread, executing it, too, concurrently, in a different thread. How is that surprising? – JB Nizet Sep 02 '17 at 21:45

1 Answers1

0

Thread.start() is the proper way to Start a Thread.

x.start();
y.start();

will start 2 new threads.

x.run();
y.run();

Will just execute the code inside your thread under the actual main Thread. This is a common mistake.

Already mentioned here

and here