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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© BlackHorse   /  2011-7-17 20:34  /  3143 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

老师在讲交通灯的时候说Threap.sleep()方法不能放在一个构造函数里,否则无法返回??
我没太想明白为什么呢?

3 个回复

倒序浏览
黑马网友  发表于 2011-7-17 21:51:14
沙发
static void sleep(long millis)  方法是没有返回值的。
构造函数必须要有返回值
回复 使用道具 举报
不可以么?
  1. public class Test {
  2.         public static void main(String[] args) {
  3.                 TestConstructor tc = new TestConstructor();
  4.                 System.out.println("helloworld");
  5.         }
  6. }

  7. class TestConstructor {
  8.         public TestConstructor(){
  9.                 try {
  10.                         Thread.sleep(5000);
  11.                 } catch (InterruptedException e) {
  12.                         // TODO Auto-generated catch block
  13.                         e.printStackTrace();
  14.                 }
  15.         }
  16. }
复制代码
以上代码正常运行 5秒钟后打印出helloworld
但是在public TestConstructor(){}却不能向外抛Exception,这我也不知道为啥。楼下请继续解答。
回复 使用道具 举报
黑马网友  发表于 2011-7-17 22:01:21
板凳

回复 藤椅 的帖子

[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]没有捕获到异常

评分

参与人数 1技术分 +1 收起 理由
老罗 + 1 很活跃呀,加分。

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马