Java认证考试实例疑难辨析(5)

5.

【知识点】

(1)Thread类的start()方法

start()方法用于启动线程的执行,也就是让run()方法开始运行。

start()方法只允许执行一次,也就是说一个线程只允许启动一次,即使执行完毕也不允许重新启动,否则会抛出IllegalThreadStateException。

【例题】

       public static void main(String[] args) {

              new Threads4().go();

 

       }

 

       public void go() {

              Runnable r = new Runnable() {

                     public void run() {

                            System.out.print("foo");

                     }

              };

              Thread t = new Thread(r);

              t.start();

              t.start();

       }

 

}
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "foo".
D. The code executes normally, but nothing is printed.
【Answer】 B

【例题辨析】

A. 可以在Eclipse开发环境中尝试录入本程序,如果编辑窗口中没有错误提示出现,通常不存在编译错误;

B. 同样,在Eclipse开发环境中尝试录入本程序,可以看到如下信息:

fooException in thread "main"java.lang.IllegalThreadStateException

       atjava.lang.Thread.start(Unknown Source)

       atThreads4.go(Threads4.java:17)

       atThreads4.main(Threads4.java:5)

上述信息说明运行时抛出了异常,这是因为Thread类的start()方法只允许执行一次,也就是说一个线程只允许启动一次,即使执行完毕也不允许重新启动;

C. 同上

D. 同上
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值