需求:多线程获取mysql某表中的数据去完成任务。具体步骤:每次从表中获取n条数据,同时修改这n条数据的状态,防止并发的其他线程在 update 之前获取到重复的数据。
实现:用事务来处理,代码如下:
// 事物处理
con.setAutoCommit(false);
String sql = "select * from table where status=0 order by Createdon desc limit ?";
psta = con.prepareStatement(sql);
psta.setInt(1, 10);
rs = psta.executeQuery();
String ids = "";
while (rs.next()) {
ids = ids + rs.getInt("id") + ",";
}
String sqlUpdate = "update table set status = ? where id in (" + ids + ")";
psta = con.prepareStatement(sqlUpdate);
psta.setInt(1, 1);
result = psta.executeUpdate();
// 事务提交
con.commit();
con.setAutoCommit(true);
结果:threadName:Thread-0,取到数据id:1
threadName:Thread-1,取到数据id:1
并发取到了同一条数据。<