为什么需要Thread.start()?

时间:2014-05-28 09:00:24

标签: java multithreading thread-sleep

当我遇到一个问题时,我正在研究Threads。如果我们可以像任何普通方法那样用类的对象直接调用run()方法那么为什么我们需要调用Thread.start()来调用run()方法..我尝试了两种方法,并且两者都得到了相同的结果

直接调用run()方法首次尝试

class Abc extends Thread
{
   public void run()
   {
      for(int i=0;i<5;i++)
      {
         System.out.println("Abc");
      }
      try
      {
          Thread.sleep(100);
      }catch(Exception e)
      {
          System.out.println("Error : "+ e);
      }
   }
}

class Xyz extends Thread
{
    public void run()
    {
       try
       {
           for(int i=0;i<5;i++)
           {
               System.out.println("Xyz");
           }
           Thread.sleep(100);
       }catch(Exception e)
       {
            System.out.println("Error : "+ e);
       }
    }
}

public class ThreadDemo 
{
    public static void main(String[] args) 
    {
        Abc ob=new Abc();
        Xyz oc=new Xyz();
        ob.run();
        oc.run();
    }
}

通过调用Thread.start()

进行第二次尝试
public class ThreadDemo 
{
    public static void main(String[] args) 
    {
        Abc ob=new Abc();
        Xyz oc=new Xyz();
        Thread t1,t2;
        t1=new Thread(ob);
        t2=new Thread(oc);
        t1.start();
        t2.start();
    }
}

5 个答案:

答案 0 :(得分:8)

如果直接调用run(),代码将在调用线程中执行。通过调用start(),可以并行创建并执行新的线程。

答案 1 :(得分:2)

如果你直接调用run(),那么所有工作都将在主线程上完成。 通过使用Thread.start,它将在主线程以外的新线程上执行;)

答案 2 :(得分:1)

要观察区别,请将睡眠时间增加到10秒以上。这显然需要Thread.start来避免第一个任务等待第二个任务。

如果您使用Thread.start,您将看到两个线程的输出立即出现。

如果你使用run,你会看到第一个输出出现,然后是10秒延迟,然后是第二个输出。

答案 3 :(得分:0)

如果直接调用run()方法,则代码将以内联方式运行。要在单独的线程中运行代码,必须调用Thread.start()

答案 4 :(得分:0)

当你在线程引用上调用start()方法时,它会创建span完全上下文区域。然后线程将具有您调用的独立堆栈。更多over start()调用OS本机线程在单独的内存上下文中启动它。

虽然run()方法调用被认为是简单的方法调用,但由于它的执行是当前堆栈,因此您不会受益于并发。

相关问题