Thread difference in the start and run approach is:
- Call start () method creates a new child thread and start
- run () method is just an ordinary method invocation Thread
Let's verify.
The following code, using the first run () method:
package thread;
public class ThreadTest {
private static void attack() {
System.out.println("Fight");
System.out.println("Current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
attack();
}
};
System.out.println("Current main thread is:" + Thread.currentThread().getName());
t.run(); // run()方法,会沿用主线程
}
}
The output is:
Current main thread is:main
Fight
Current thread is:main
Then start () method:
package thread;
public class ThreadTest {
private static void attack() {
System.out.println("Fight");
System.out.println("Current thread is:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
attack();
}
};
System.out.println("Current main thread is:" + Thread.currentThread().getName());
t.start(); // 会创建新的线程
}
}
The output is:
Current main thread is:main
Fight
Current thread is:Thread-0
Why run and start a different result may know, start a new thread is created, but will not run, it's just follow the main thread only.
We can also start with a look at the source method Why create a new thread.
Into the start () source code, as follows:
then see start0 ():
then log: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/ to query an external non-Java source code, as follows:
Click browse, because Thread.class located in java.lang directory, so we enter the / src / share / native / java / lang directory, find Thread.c file
open Thread.c file, search for "start0",
and then we went to see jvm source, http://hg.openjdk.java.net/jdk8u/ return to this directory, click the hotspot,
and then click browse,
then enter / src / share / vm / prims directory, find jvm.cpp files, Java used by some of the native the method in it,
open the file, search JVM_StartThread,
enter thread_entry,
the process represented by FIG follows: