我们都知道java的接口是不能实例化的,而我们都知道Runnable是一个接口,在多线程的时候经常会看到这样的代码new Thread(new Runnable(void run(){...}));这时候就困惑了。
其实这不是实例化Runnable接口,而是先创建一个实现Runnable接口的没有名字的类之后再实例化这个新的类,{...}是这个类的内容。而Thread方法有个构造函数是需要传入实现Runnable类的参数的 public Thread(Runnable target) 。
然而为什么把另一个线程要执行的内容放在run方法里,然后Thread对象start一下就执行了呢?
我原以为start()方法里调用run()了,
模拟一下,就像这样
public interface myRunnable {
void run();
}
public class Thread {
myRunnable p;
public Thread(myRunnable p)
{
this.p = p;
}
public void start()
{
p.run();
}
public static void main(String[] args)
{
Thread w =new Thread(new myRunnable()
{
public void run()
{
System.out.println("run");
}
});
w.start();
}
}
其实不然,
以下是jdk中的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".
*/
if (threadStatus != 0)
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);
boolean started = false;
try {
start0();
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 */
}
}
}
start调用了start0本地方法,然后新产生一个线程调用run方法,见http://blog.csdn.net/xiancaieeee/article/details/7767895
补充一下,以前一直搞不清楚多线程怎样控制一个对象,其实只要多new几次Thread每次传入一个同一个对象即可,这样可以实现多个线程共享同一个目标对象,非常适合处理同一个资源的情况(相对于继承Thread类的优点),在run方法中如果访问当前进程必须用,Thead.currentThread()方法,而继承Thread方法直接使用this可以获得当前线程。