ReentrantLock是并发包(java.util.concurrent)中提供的一个更为方便的控制并发资源访问的类,且和synchronized语法
达到的效果是一致的。
主要方法有:
1.lock 加锁
2.unlock 解锁
eg:
public class UserManagerWithLock {
private List<String> userList = new ArrayList<String>();
//我们可以定义一把锁
ReentrantLock lock = new ReentrantLock();
public boolean addUser(String user){
boolean succeed = false;
lock.lock();
try{
if(!userList.contains(user)){
System.out.println(Thread.currentThread().getName() + "--->" +"我来了" + "--->" + user);
succeed = userList.add(user);
System.out.println(userList);
}}finally{
lock.unlock();
}
return succeed;
}
}
达到的效果是一致的。
主要方法有:
1.lock 加锁
2.unlock 解锁
eg:
public class UserManagerWithLock {
private List<String> userList = new ArrayList<String>();
//我们可以定义一把锁
ReentrantLock lock = new ReentrantLock();
public boolean addUser(String user){
boolean succeed = false;
lock.lock();
try{
if(!userList.contains(user)){
System.out.println(Thread.currentThread().getName() + "--->" +"我来了" + "--->" + user);
succeed = userList.add(user);
System.out.println(userList);
}}finally{
lock.unlock();
}
return succeed;
}
}
eg:
private boolean addIfUnderCorePoolSize(Runnable firstTask) {
Thread t = null;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (poolSize < corePoolSize && runState == RUNNING)
t = addThread(firstTask);
} finally {
mainLock.unlock();//放在finally中,锁一定会释放,否则抛出异常或其它原因时,锁没释放,一起被持有,就不妙了
}
if (t == null)
return false;
t.start();
return true;
}