几道问题,求大侠给出正解!!
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));
}
}
}
------解决方案-------------------- "When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object 's lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object.
Or you can synchronize on the current instance (this) as in the code above. Since that 's the same instance that synchronized methods lock on, it means that you could always replace a synchronized method with a non-synchronized method containing a synchronized block. In other words, this: