首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

三个标题,帮忙具体解释一下

2011-12-21 
三个题目,帮忙具体解释一下1.What’sthedifferencebetweenAandB?A.classTest{publicvoidtest(){synchronize

三个题目,帮忙具体解释一下


1.What’s   the   difference   between   A   and   B?

 

A.

class   Test

{

public   void   test()

{

        synchronized(this)

        {

                ...

        }

}

}

  B.

class   Test

{

      public   synchronized   void   test()

      {

              ...  

      }

 

}
 

 

2.           Why   the   init()   method   must   be   private?   Please   provide   an   example   to   explain   it.

 

class   Test

{

public   Test()

{

      init();

}

 

private   void   init()

{

      …

}

}

 

3.           Find   problems   in   this   code   snippet:

 

class   Test

{

public   static   void   executeQuery(   String   connectionName,     String   statementText)   throws   SQLException

{

        Connection   connection   =   null;

        try  

{

        //Get   a   connection   from   connection   pool

                connection   =   manager.getConnection(connectionName);

                Statement   statement   =   connection.createStatement();

                ResultSet   resultSet   =  

                                    statement.executeQuery(statementText);

                for   (int   i   =   0;   resultSet.next();   i++)  

                {

                        ...

                }

 

                resultSet.close();

                statement.close();

 

                return   ;

        }

        catch   (SQLException   e)  

        {

                throw(new   SQLException(statementText));

        }

}

}


------解决方案--------------------


1、还真不知道有什么区别,都是用this做锁,硬要说的话,一个在调函数的时候锁,一个进了函数后再上的锁
2, init如果public的话,可以被外界调用,相当可以重新初始化了

3,最明显的就是connection没关闭,然后关闭最好写在finally里面,那个return没必要
[解决办法]
第二道题:构造函数中惟一可以安全调用的函数便是 "base class中的final函数 "(private函数一样成立,因为它们天生是final).
例子:
abstract class Glyph{
abstract void draw();
Glyph(){
System.out.println( "Glyph() before draw() ");
draw();
System.out.println( "Glyph() after draw() ");
}
}

class RoundGlyph extends Glyph{
int radius=1;
RoundGlyph(int r){
radius=r;
System.out.println( "RoundGlyph.RoundGlyph(),radius= "+radius);
}
void draw(){
System.out.println( "RoundGlyph.draw(),radius= "+radius);
}
}

public class PolyConstructors{
public static void main(String[]args){
new RoundGlyph(5);
}
}

java编程思想里专门讲到了这一问题
[解决办法]
1:第一个是锁部分代码 第二个是锁一个方法。第一个的执行速率要快一些。

热点排行
Bad Request.