方法一
构造函数传入Runnable,重写run方法
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
方法二
Thread实现run方法
new Thread(){
@Override
public void run() {
}
}.start();
源码分析:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
// Android-changed: throw if 'started' is true
if (threadStatus != 0 || started)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
started = false;
try {
nativeCreate(this, stackSize, daemon);
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native static void nativeCreate(Thread t, long stackSize, boolean daemon);
启动线程之后,最终调用了native层的nativeCreate方法,最后native会调用Thread的run方法,此时run方法就执行在子线程了。
@Override
public void run() {
if (target != null) {
target.run();
}
}
这时我们发现这里有一个target,查看一下Thread的构造函数
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
Thread parent = currentThread();
if (g == null) {
g = parent.getThreadGroup();
}
g.addUnstarted();
this.group = g;
this.target = target;
this.priority = parent.getPriority();
this.daemon = parent.isDaemon();
setName(name);
init2(parent);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
tid = nextThreadID();
}
我们发现其实这个target就是我们传入的runnable,这也就解释了为啥传入runnable也可以执行子线程。那么问题来了我们是否可以来个这样的骚操作(线程:这是人干出来的事么)?
new Thread(new Runnable() {
@Override
public void run() {
Log.e("Thread",Thread.currentThread().getId()+"Runnable");
}
}){
@Override
public void run() {
//这一行影响能否执行Runnable里的run方法
super.run();
Log.e("Thread",Thread.currentThread().getId()+"run");
}
}.start();
经打印发现两个方法都能执行,而且是同一个子线程里。