Two ways to customize a thread
Customize the implementation class for a runnable interface, and then construct a thread that passes a runnable interface class to Thread.
New thread or write a thread subclass to overwrite its run method. (New thread and overwrite the Run method is actually a way of anonymous inner class)
Sample code
public static void Main (string[] args {
new Thread () {new Runnable () {@Override the public
Void Run () {
System . OUT.PRINTLN ("Create thread by passing a runnable target!");
}
). Start ();
New Thread () {
@Override public
void Run () {
System.out.println (' Create Thread by Override Run Method! ');
};
}. Start ();
}
The above methods, which correspond to the 1 and 22 construction threads, are designed with the following instructions:
1. For the first paragraph I passed directly to the anonymous runnable instance, you can customize a runnable instance, and then new Thread (runnable) This form to get thread;
2. For the second paragraph, you can specifically define a class to extends the thread base class, and then new this thread class.
3. For both paragraphs are direct new thread to create an anonymous class object, you can define a variable thread1, thread2, and then use Thread1.start () Thread2.start () to start the thread;
SOURCE Analysis
What's the difference between the two, the final effect is the same, at the source level, the default run method of thread (not overwritten) is the Run method that invokes target, which is not empty, and target is our incoming Runnable interface class.
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) { c14/>}}}
The start of the thread eventually invokes the native start0, which causes the JVM virtual machine to invoke the thread's Run method.
public void Run () {
if (target!= null) {
target.run ();
}
}
The target here is a Runnable object in thread.
Private Runnable target;
Summarize
The Run method of the replication thread is the Run method that the thread executes when start.
Incoming runnable, the thread executes the default run method when start, and the Run method invokes the target's Run method on the incoming target.
The effect is the same, and this is just to help us look at the code details differences.
The above is a small set to introduce the Java thread in the start and run method comprehensive analysis, hope to help everyone, if you want to learn more content please pay attention to cloud habitat community!