美文网首页
java_行级锁

java_行级锁

作者: 走停2015_iOS开发 | 来源:发表于2021-01-27 10:44 被阅读0次
    • 悲观锁(行级锁):事务必须排队执行 数据按住了 不允许并发(行级锁:select后面添加for update)
    • 乐观锁: 支持并发 事务也不需要排队 只不过需要一个版本号

    开启俩个程序进行演示

    1.程序01启动后开启悲观锁进行查询 在没有提交之前 02会被卡住不能查询
    2.等待程序01commit完成后,程序02才能继续执行
    
    public class lockTest01 {
        public static void main(String[] args) {
            Connection con = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                con = DBUtil.getConnect();
                con.setAutoCommit(false);
                String sql = "select *from t_student where classno = ? for update";
                ps = con.prepareStatement(sql);
                ps.setInt(1,102);
                rs = ps.executeQuery();
                while (rs.next()){
                    System.out.println(rs.getString("sno")+","+rs.getString("sname"));
                }
                con.commit();
            } catch (SQLException throwables) {
                try {
                    con.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                throwables.printStackTrace();
            }finally {
                DBUtil.close(con,ps,rs);
            }
        }
    }
    
    public class lockTest02 {
        public static void main(String[] args) {
            Connection con = null;
            PreparedStatement ps = null;
            try {
                con = DBUtil.getConnect();
                con.setAutoCommit(false);
                String sql = "update t_student set grade = grade*0.8 where classno =?";
                ps = con.prepareStatement(sql);
                ps.setInt(1,102);
                int count = ps.executeUpdate();
                System.out.println(count);
                con.commit();
            } catch (SQLException throwables) {
                try {
                    con.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                throwables.printStackTrace();
            }finally {
                DBUtil.close(con,ps,null);
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java_行级锁

          本文链接:https://www.haomeiwen.com/subject/ddvozktx.html