我先调用start然后运行,但输出就像运行2个不同的线程

时间:2017-09-02 19:09:39

标签: java multithreading

我先调用start,然后调用run。当我首先运行run()然后start()时,run被视为一种方法并完全运行,然后调用start,但这样我输出为:

  

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

为什么,一旦调用运行,它是否完全运行?

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();
  }
}

1 个答案:

答案 0 :(得分:0)

Thread.start()是启动线程的正确方法。

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

将启动2个新主题。

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

只需在实际的主线程下执行线程内的代码。 这是一个常见的错误。

Already mentioned here

and here