当用Thread的子类构造创建多线程时,并同时传入Runnable覆盖run方法时,此时执行的run方法是

package com.giserve.test;

public class ThreadTest {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(1000);
						System.out.println("Thread1::"+Thread.currentThread().getName());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(1000);
						System.out.println("Thread0::"+Thread.currentThread().getName());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
		}.start();
	}
}

结果是:

Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0
Thread0::Thread-0

在JDK源码中Thread线程中的run是这样实现的

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
结论:
target代表的是构造Thread时传入的Runable对象,疑问为什么会是Thread-0,原因是当子类覆盖父类后,上面的run方法的target就不存在了。所以执行的run方法就是Thread子类的。





你可能感兴趣的:(心得)