为什么需要Thread.start()? [英] Why Thread.start() is needed?

查看:562
本文介绍了为什么需要Thread.start()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想到一个问题时,我正在研究线程..如果我们可以像任何普通方法一样直接使用类的对象调用run()方法,那么为什么我们需要调用Thread.start()来进行调用run()方法..我尝试了如图所示的两种方法,并获得了相同的结果

I was working on Threads when a question struck to my mind..If we can directly call run() method with the object of a class like any ordinary method then why do we need to call Thread.start() to call run() method..I tried both the methods as shown and got same result with both of them

通过直接调用run()方法的第一次尝试

First attempt by calling run() method directly

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()进行第二次尝试

Second attempt by calling 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();
    }
}

推荐答案

如果直接调用run(),则代码将在调用线程中执行.通过调用start(),将创建​​并并行执行一个新线程.

If you call run() directly, the code gets executed in the calling thread. By calling start(), a new Thread is created and executed in parallel.

这篇关于为什么需要Thread.start()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆