Created
October 27, 2018 02:40
Read Committed Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyRunner implements Runnable { | |
public void run() { | |
System.out.println(Thread.currentThread().getName() + ":连接数据库..."); | |
Connection connection = null; | |
try { | |
connection = DriverManager.getConnection(RepeatableRead.DB_URL, RepeatableRead.USER, RepeatableRead.PASS); | |
connection.setAutoCommit(false); | |
//connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); | |
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); | |
String querySql = "select * from account where id=?"; | |
synchronized (this) { | |
PreparedStatement queryStmt = connection.prepareStatement(querySql); | |
queryStmt.setInt(1, 1); | |
ResultSet set = queryStmt.executeQuery(); | |
set.next(); | |
int amount = set.getInt("amount"); | |
System.out.println(Thread.currentThread().getName() + ":Amount=" + amount); | |
Thread.sleep(1000); | |
// 读取了数据,未提交事务。 | |
String updateSql = "update account set amount=? where id=1"; | |
PreparedStatement updateStmt = connection.prepareStatement(updateSql); | |
updateStmt.setInt(1, amount + 100); | |
int count = updateStmt.executeUpdate(); | |
if (count > 0) { | |
set = queryStmt.executeQuery(); | |
set.next(); | |
amount = set.getInt("amount"); | |
System.out.println(Thread.currentThread().getName() + ":更新成功...|" + amount); | |
} | |
connection.commit(); | |
} | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment