当然是第一中方法效率高了
如果您老是调用run方法,在第2中方法中就会不停地创建对象
a.占用运行时间
b.开辟更多的内存空间
从时间复杂度和空间复杂度上来说,第一中好

解决方案 »

  1.   

    差不多,“test”都在常量池中,没有反复创建新对象; 第二种变量作用域小,我觉得好些这样看起来更好点吧
    class C implements Runnable{
      public void run() {
        String tttttttttt = null;
        while(true) {
          try {
            tttttttttt = "test";
            tttttttttt = null;
            Thread.sleep(10);
          }catch(Exception e){
          }
        }
      }
    }
      

  2.   

    学习ing
    难到您如果不停的调用run方法
     String tttttttttt = "test";
    此句代码没有反复创建新的String对象tttttttttt
      

  3.   

    由于有常量池你可以试试:
             String s="test";
             while(true){
                String ttt = "test";
                System.out.println(ttt==s);
                ttt=null;
             }
      

  4.   

    不好意思,在麻烦各位一下,如果
    class D implements Runnable{
      public void run() {
        String tttttttttt = null;
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        while(true) {
          .... 
          ....
          while(rs.next())
            try {
              tttttttttt = rs.getString(1);//这里的值每次都可能不一样。
              tttttttttt = null;
              Thread.sleep(10);
            }catch(Exception e){
            }
           }
        }
      }
    }
    tttttttttt这个变量的值可能每次都不一样,那应该定义成全局变量好呢,还是局部变量好啊。
      

  5.   

    java里没有全局变量的说法成员变量或者函数里的局部变量当然作用域越小越好
    你的ttttttt如果类D的其它函数并不使用,当然是定义为局部变量了。
      

  6.   

    当然作用域越小越好 同意一个类里的变量尽量要私有化,局部化,因为是这个类的属性,其他人不应该直接调用,或者改变。要改变应该通过类提供的public方法来改变。