黑马程序员技术交流社区
标题:
为什么Thread.sleep()方法不能放在构造函数里
[打印本页]
作者:
BlackHorse
时间:
2011-7-17 20:34
标题:
为什么Thread.sleep()方法不能放在构造函数里
老师在讲交通灯的时候说Threap.sleep()方法不能放在一个构造函数里,否则无法返回??
我没太想明白为什么呢?
作者:
匿名
时间:
2011-7-17 21:51
static void sleep(long millis) 方法是没有返回值的。
构造函数必须要有返回值
作者:
张炜
时间:
2011-7-17 21:53
不可以么?
public class Test {
public static void main(String[] args) {
TestConstructor tc = new TestConstructor();
System.out.println("helloworld");
}
}
class TestConstructor {
public TestConstructor(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
复制代码
以上代码正常运行 5秒钟后打印出helloworld
但是在public TestConstructor(){}却不能向外抛Exception,这我也不知道为啥。楼下请继续解答。
作者:
匿名
时间:
2011-7-17 22:01
标题:
回复 藤椅 的帖子
[code]public class TEST {
public static void main(String[] args)
{
TestConstructor tc = new TestConstructor();
System.out.println("helloworld");
}
}
class TestConstructor
{
public TestConstructor()
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("异常");
e.printStackTrace();
}
}
}[/code]没有捕获到异常
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2