Two ways to customize threads
Customize a runnable interface implementation class, and then construct a thread, that is, pass a runnable interface class to the thread.
new thread or write a thread subclass to override its run method. (new a thread and overriding the run method is actually a way to anonymous inner class)
Sample code
public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {System.out.println("create thread by passing a runnable target !");}}).start();new Thread(){@Overridepublic void run() {System.out.println("create thread by Override run method !");};}.start();}The above-mentioned methods for constructing threads of 1 and 2 are designed with anonymous class objects because of the code writing method. The following auxiliary instructions are now made:
1. For the first paragraph, I directly passed in an anonymous runnable instance. You can customize a runnable instance and then get thread in the form of new thread(runnable);
2. For the second paragraph, you can specifically define a class to extends thread base class, and then new this new thread class.
3. For these two segments, create anonymous class objects directly with new thread. You can define a variable thread1 and thread2, and then use thread1.start() thread2.start() to start the thread;
Source code analysis
What is the difference between these two methods? The final effect of the two is the same. From the source code level, the default run method of thread (if it is not overwritten) is the run method that calls target (the target is not empty). target is the runnable interface class we passed in.
public synchronized void start() {if (threadStatus != 0)throw new IllegalThreadStateException();group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {}}}The thread's start will eventually call native start0, which will cause the jvm virtual machine to call the thread's run method.
public void run() {if (target != null) {target.run();}}Here the target is a runnable object in Thread
private Runnable target;
Summarize
The run method of rewriting thread is the run method executed by the thread when starting.
When passing runnable, the thread executes the default run method when starting. The run method will call the passed target and call the target's run method.
The effect of both is the same, here is just to help us see the differences in the code details.
The above is a comprehensive analysis of the start and run methods in Java threads introduced by the editor. I hope it will be helpful to everyone. If you want to know more, please pay attention to Wulin.com!