ReenTrantLock简单使用
/**
* @ClassName:MReenTrantLock
* @Description:TODO加入锁,保证一次执行,同时也防止并发影响数据有效性
* @Author:ZY
* @Date:2019/6/24 0024 22:34
* @Version:1.0
**/
public class MReenTrantLock extends Thread {
private static Integer num = 100;
//为true则是公平锁
private static Lock lock = new ReentrantLock(false);
public void run () {
for (int i = 0; i < 100; i++) {
lock.lock();
try {
if (num == 0) {
break;
}
num--;
System.out.println(num);
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
MReenTrantLock mReenTrantLock = new MReenTrantLock();
for (int i = 0; i < 1000; i++) {
Thread thread = new Thread(mReenTrantLock);
thread.start();
}
}
}