我正在编写一些没有给我预期结果的尖峰代码。
我有一个基本上是几行计数器的表。其他表使用这些行来生成应该是唯一 ID 的内容。当我运行下面的代码时,我例外的是到达 select 语句的第一个线程将获取该行或表上的锁,从而停止对唯一 id 值的所有读取或写入。然而,第二个线程总是在第一个线程之前完成,因为它被休眠了 1 秒,因此它们都读取相同的值并写入相同的值,所以它只增加一次,而不是我例外的两次。
我的代码有什么问题,还是我对隔离级别的理解不正确?
我已经删除了样板代码。使用 MySQL 数据库的标准 sql.Connection。
private void incrementValue() {
        connection
                .setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        statement = connection.createStatement();
        System.out.println(Thread.currentThread().getName()
                + " doing select");
        resultSet = statement.executeQuery("select * from counter");
        System.out.println(Thread.currentThread().getName()
                + "after select");
        if (counter++ == 0) {
            Thread.sleep(1000);
        }
        String incrementedValue = getIncrementedValue(resultSet);
        statement.executeUpdate("update counter set counter='"
                + incrementedValue + "'");
}
private String getIncrementedValue(ResultSet resultSet) throws SQLException {
    String value = "";
    if (resultSet.next()) {
        System.out.println(Thread.currentThread().getName() + "Value was "
                + resultSet.getString(1));
        value = (new Integer(resultSet.getString(1)) + 1) + "";
    }
    return value;
}
这是从 main 调用的
public static void main(String[] args) {
    DatabaseExample databaseExample = new DatabaseExample();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            DatabaseExample databaseExample = new DatabaseExample();
            databaseExample.incrementValue();
        }
    };
    new Thread(runnable).start();
    databaseExample.incrementValue();
}