public class LockTest extends SpringTestBase {
@Resource
private CommonMapper commonMapper;
@Test
public void lock() {
new LockThread(commonMapper, "lock1thread").start();
new LockThread(commonMapper, "lock2thread").start();
new LockThread(commonMapper, "lock3thread").start();
}
}
public class LockThread extends Thread {
private CommonMapper commonMapper;
private String name;
public LockThread(CommonMapper commonMapper, String name) {
this.commonMapper = commonMapper;
this.name = name;
}
@Override
public void run() {
super.setName(name);
Object o = commonMapper.selectObjSql("select t.islock from mylock t where t.id='1' and t.name='test1'");
int lock = Integer.parseInt(o.toString());
System.out.println(lock);
if (lock == 0) {
System.out.println(super.getName() + "获取到了0 进行枷锁");
int i = commonMapper.updateSql(" update mylock t set t.islock=1 where t.id='1' and t.name='test1' and t.islock='0' ");
if (i > 0) {
System.out.println(super.getName() + "当前线程获取到锁");
/**
* 需要解决并的业务代码
*/
//释放锁
int unlock = commonMapper.updateSql(" update mylock t set t.islock=0 where t.id='1' and t.name='test1' and t.islock='1' ");
System.out.println(unlock > 0 ? "释放锁成功" : "释放锁失败");
} else {
System.out.println(super.getName() + "当前线程没有获取到锁");
}
} else {
System.out.println(super.getName() + "当前线程没有获取到锁!");
}
}
}
测试效果是可以,不知道有没有问题,请大佬赐教.
测试结果:
lock2thread获取到了0 进行枷锁
lock1thread当前线程获取到锁
lock3thread当前线程没有获取到锁
lock2thread当前线程没有获取到锁
释放锁成功
猜你喜欢:暂无回复。