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();
}
}
}