A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© job 中级黑马   /  2014-4-25 22:56  /  1310 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 job 于 2014-4-26 19:32 编辑
  1. class ThreadTest
  2. {
  3.         public static void main(String[] args)
  4.         {

  5.                 new Thread(new Runnable()
  6.                 {
  7.                         public void run()
  8.                         {
  9.                                 System.out.println("runnable run");
  10.                         }
  11.                 })
  12.                 {
  13.                         public void run()
  14.                         {
  15.                                 System.out.println("subThread run");
  16.                         }
  17.                 }.start();
复制代码
当时,稍微明白点,现在回过头来再看又想不通了,结果是subthread.run,求高手指点!

评分

参与人数 1技术分 +1 收起 理由
SyouRai_Tsk + 1

查看全部评分

5 个回复

倒序浏览
  1. class ThreadTest
  2. {
  3.         public static void main(String[] args)
  4.         {

  5.                 new Thread(new Runnable()//这里一个匿名内部类实现的是Runnable接口,
  6.                 {
  7.                         public void run()
  8.                         {
  9.                                 System.out.println("runnable run");
  10.                         }
  11.                 })
  12.                 {
  13.                         public void run()
  14.                         {
  15.                                 System.out.println("subThread run");//这个是Thread的匿名内部类,用的是它的start
  16.                         }
  17.                 }.start();
复制代码
回复 使用道具 举报
private Runnable target;
public void run() {
        if (target != null) {
            target.run();
        }
    }

以上是java  Thread类的元代码
你将Runnable接口传入Thread类中,是将Runnable接口传给target属性,然后在运行时Thread的run方法去找target属性的run方法.
你这段代码最后将Thread类中的run方法重写了,就是说Thread的run方法中只有你写的{

16.                                System.out.println("subThread run");

17.                        }
也就无法去找target属性的run方法了

评分

参与人数 1技术分 +1 收起 理由
SyouRai_Tsk + 1

查看全部评分

回复 使用道具 举报
WO.瘾姓埋銘 发表于 2014-4-25 23:27
private Runnable target;
public void run() {
        if (target != null) {

这个解释太给力了!
回复 使用道具 举报
本帖最后由 土突突 于 2014-4-26 11:55 编辑

可以简单分析下你的代码:
  1. new Thread(new Runnable()
  2.                 {
  3.          public void run()
  4.            {
  5.                 System.out.println("runnable run");
  6.            }
  7. })  /*以括号结束,相当于new Thread(t)  其中t是实现了Ruannable接口的匿名类对象并重写了Thread的run方法。如在此调用start()就会打印runnable run*/
复制代码
  1. {/*紧跟一对大括号,相当于定义了一个继承Thread类的匿名类对象,并再次重写了Thread的run方法*/
  2.         public void run()
  3.           {
  4.                System.out.println("subThread run");
  5.           }
  6.                 }.start();  /*调用start() 方法就会调用该匿名类对象的run方法,既第二个run方法,该匿名类是通过基类的Thread(Runnable target)构造函数类进行继承的*/
复制代码


回复 使用道具 举报
那个下面的大括号里面的内容相当于 匿名子类吧好像 你覆盖了上面写的实现Runnable类的run方法所以执行的run方法是下面大括号里面的run方法
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马