CNET中国旗舰网站

ZDNet China | CNET科技资讯网 | 政府采购 | 行业网站联盟





 
标题: [原创] SCJP考试试题解析十二
mesum
超级会员
Rank: 4



UID 321006
精华 0
积分 1811
帖子 73
威望 722
ZD币 160 元
阅读权限 90
注册 2008-4-21
状态 离线
  楼主
发表于 2008-6-12 21:04  资料  个人空间  短消息  加为好友 
开发者在线

SCJP考试试题解析十二

SCJP考试试题解析十二


我的QQ号:2535279


www.javaedu.com.cn


public class Certkiller3 implements Runnable{
        
        public void run(){
            System.out.print("running");
        }
        
        public static void main(String[] args){
            Thread t = new Thread(new Certkiller3());
            t.run();
            t.run();
            t.start();
        }
}

What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".

在这个程序中,大家都会知道t.start()肯定会启动一次线程,那么t.run()会不会启动线程呢.在API中,我找到了答案."如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。"

在这个程序中,线程t是使用独立的Runnable运行对象构造的,所以,它会调用run()方法.



还有另外一种情况就是,我自己定义一个类去继承了Thread类,覆盖了它的run()方法,当用这个子类的对象去调用run()方法时,它也会执行run()方法的内容,这是因为,Thread类本身已经实现了Runnable接口,当我们用子类去生成一个对象时,它隐含的将自身做为一个参数传递进去.这也是一个独立的Runnable运行对象.例如:
public class Certkiller3 extends Thread {

    public void run() {
        System.out.print("running");
    }
    public static void main(String[] args) {
        Thread t = new Certkiller3();
      t.run();
        t.run();
        t.start();
}
}

输出结果:runningrunningrunning

如果,在程序中,Thread类的对象是以下面这种形式定义的话Thread t = new Thread();那么,t.run()那么,将不会执行任何操作并且返回.

所以,这个题目的答案是:E

当然,用Runnable对象作为参数定义一个Thread对象,还有下面这种方法,这里写出来仅供大家参考.


那么我们来看下一下程序:

public calss SimpleThread{

    public static void main(String[] args){
        Thread t = new Thread(new Runnable(){
            public void run(){
                System.out.print("running");
            }
        });
        t.run();
        t.run();
        t.start();
    }
}

输出结果:runningrunningrunning




顶部
热点频道推荐: C/S开发| 数据库| WEB开发| 嵌入式| 项目管理|
 



当前时区 GMT+8, 现在时间是 2009-7-4 10:27

  Powered by Discuz! 5.5.0 © 2001-2007 Comsenz Inc.
Processed in 0.062333 second(s), 4/3 queries

清除 Cookies - 联系我们 - ZDNetChina中文社区 - 无图版