ReentrantLock重入锁
重入锁,在需要同步的代码部分进行锁定,使用完毕之后一定要释放锁。
实例方式:
ReentrantLock lock = new ReentrantLock(true) ;
后面有个 Boolean 类型的 fair 参数,是标识该锁是否公平的,默认 不公平,公平的意思就是 锁的给与基于调用顺序,先调用的,先获取,不公平则是遵循cpu调用规则,默认不公平效率更高。
举个栗子:
public class Main3 implements Callable<String> {
private ReentrantLock lock = new ReentrantLock(true) ;
private int i =10;
@Override
public String call() throws Exception {
lock.lock();
System.out.println( Thread.currentThread().getName() + "==>" + --i );
lock.unlock();
return "" ;
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(10);
Main3 task = new Main3();
for (int i = 0; i < 10; i++) {
pool.submit( task );
}
pool.shutdown();
}
}
Condition,类似wait() 和 notify()
实例方式:
private ReentrantLock lock = new ReentrantLock(true) ;
private Condition condition = lock.newCondition();
举个栗子:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main4 {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void method1(){
try {
lock.lock();
System.out.println