问题
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
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();
}
}
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();
}
}
回答1:
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.
回答2:
If you directly call run(), then all the work will be done on the main thread. By using Thread.start, then it will executed on a new thread other than the main thread ;)
回答3:
To observe what the difference is, increase your sleep calls to something longer like 10 seconds. This will make it obvious that you need Thread.start
to avoid the first task waiting on the second.
In the case where you use Thread.start
, you will see that output of both threads appears immediately.
In the case where you use run
, you will see that the output of the first appears, then a 10 second delay, then the output of the second.
回答4:
If you call run()
method directly then code will run inline. To run the code in separate thread it is necessary to call Thread.start()
.
回答5:
When you call start() method on thread reference it create span entirely context area. Then thread will have independent stack from where you are calling. More over start() invokes OS native thread to start it in separate memory context.
While run() method invocation considered as simple method call, and you won't have benefit of concurrency as its executing is current stack.
来源:https://stackoverflow.com/questions/23907118/why-thread-start-is-needed