The difference between start Java multithreading and concurrent threads and run the -8.2

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:
Here Insert Picture Description
then see start0 ():
Here Insert Picture Description
then log: http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/ to query an external non-Java source code, as follows:
Here Insert Picture Description
Click browse, because Thread.class located in java.lang directory, so we enter the / src / share / native / java / lang directory, find Thread.c file
Here Insert Picture Description
open Thread.c file, search for "start0",
Here Insert Picture Description
and then we went to see jvm source, http://hg.openjdk.java.net/jdk8u/ return to this directory, click the hotspot,
Here Insert Picture Description
and then click browse,
Here Insert Picture Description
then enter / src / share / vm / prims directory, find jvm.cpp files, Java used by some of the native the method in it,
Here Insert Picture Description
open the file, search JVM_StartThread,
Here Insert Picture Description
enter thread_entry,
Here Insert Picture Description
the process represented by FIG follows:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/tanwenfang/article/details/92384531