JDK并发包详细总结

同步控制工具类

ReentrantLock可重入锁

Condition

Semaphore信号量

ReadWriteLock读写分离锁

CountDownLatch倒数计时器

CyclicBarrier循环栅栏

LockSupport阻塞线程

并发容器

Collections.synchronizedMap

ConcurrentHashMap

BlockingQueue

CopyOnWriteArrayList

同步控制工具类 ReentrantLock

简而言之, 就是自由度更高的synchronized, 主要具备以下优点.

可重入: 单线程可以重复进入,但要重复退出

可中断: lock.lockInterruptibly()

可限时: 超时不能获得锁,就返回false,不会永久等待构成死锁

公平锁: 先来先得, public ReentrantLock(boolean fair), 默认锁不公平的, 根据线程优先级竞争.

示例 

public class ReenterLock implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();
    public static int i = 0;

@Override
    public void run() {
        for (int j = 0; j < 10000; j++) {
            lock.lock();
            // 超时设置
//            lock.tryLock(5, TimeUnit.SECONDS);
            try {
                i++;
            } finally {
                // 需要放在finally里释放, 如果上面lock了两次, 这边也要unlock两次
                lock.unlock();
            }
        }
    }

public static void main(String[] args) throws InterruptedException {
        ReenterLock tl = new ReenterLock();
        Thread t1 = new Thread(tl);
        Thread t2 = new Thread(tl);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}

中断死锁

线程1, 线程2分别去获取lock1, lock2, 触发死锁. 最终通过DeadlockChecker来触发线程中断.

public class DeadLock implements Runnable{

public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    int lock;

public DeadLock(int lock) {
        this.lock = lock;
    }

@Override
    public void run() {
        try {
            if (lock == 1){
                lock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){}
                lock2.lockInterruptibly();

}else {
                lock2.lockInterruptibly();
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){}
                lock1.lockInterruptibly();

}
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            if (lock1.isHeldByCurrentThread())
                lock1.unlock();
            if (lock2.isHeldByCurrentThread())
                lock2.unlock();
            System.out.println(Thread.currentThread().getId() + "线程中断");
        }
    }

public static void main(String[] args) throws InterruptedException {
        DeadLock deadLock1 = new DeadLock(1);
        DeadLock deadLock2 = new DeadLock(2);
        // 线程1, 线程2分别去获取lock1, lock2. 导致死锁
        Thread t1 = new Thread(deadLock1);
        Thread t2 = new Thread(deadLock2);
        t1.start();
        t2.start();
        Thread.sleep(1000);
        // 死锁检查, 触发中断
        DeadlockChecker.check();

}
}

Condition

类似于 Object.wait()和Object.notify(), 需要与ReentrantLock结合使用.

具体API如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/8791015b7c833f8476df32253f13fed6.html