并发编程

Atomic类 - 线程安全类型

Atomic类的相关操作,底层实现依赖Unsafe类中的原子指令实现(如CAS) + volatile

public class AtomicInteger extends Number implements java.io.Serializable {
    private static final long serialVersionUID = 6214790243416807050L;

    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value;

    // 原子操作 - 比较并设置
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
}

// 计数器 - Test
public class AtomicTest {
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        for(int i = 0; i < 1024; i++){
            new Thread(()->{
                int k = count.getAndIncrement();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(k);
            }).start();
        }
    }
}

阻塞队列 - BlockingQueue

阻塞队列为生产者消费者模式的具体实现,实现消息生产和消费的异步化(解耦)

阻塞队列类型

-- BlockingQueue -- describe
ArrayBlockingQueue 数组实现的有界阻塞队列, 此队列按照先进先出(FIFO)的原则对元素进行排序。
LinkedBlockingQueue 链表实现的有界阻塞队列, 此队列的默认和最大长度为Integer.MAX_VALUE。此队列按照先进先出的原则对元素进行排序
PriorityBlockingQueue 支持优先级排序的无界阻塞队列, 默认情况下元素采取自然顺序升序排列。也可以自定义类实现 compareTo()方法来指定元素排序规则,或者初始PriorityBlockingQueue时,指定构造参数 Comparator 来对元素进行排序。
DelayQueue 优先级队列实现的无界阻塞队列
SynchronousQueue 不存储元素的阻塞队列, 每一个 put 操作必须等待一个 take 操作,否则不能继续添加元素
LinkedTransferQueue 链表实现的无界阻塞队列
LinkedBlockingDeque 链表实现的双向阻塞队列

阻塞队列API

抛出异常 特殊值 阻塞 超时
插入 add(e) offer(e) - true/false put(e) offer(e, time, unit) - 超时fasle
移除 remove(e) poll() - E/NULL take() poll(time, unit) - 超时NULL
检查 element() peek() - E/NULL
// 内部实现是lock + 两个condition
public class BlockingQueueTest {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(4);

        // 第一组,会抛出异常
        queue.add(1);           // 插入元素
        queue.remove();         // 移除元素
        queue.element();        // 检索但不移除队首元素

        // 第二组,返回特殊值 offer - false, pool - NULL, peek - NULL
        queue.offer(2);     // 插入元素
        queue.poll();           // 移除元素
        queue.peek();           // 检索但不移除队首元素

        // 第三组,阻塞
        queue.put(3);       // 插入元素 - 队满阻塞
        queue.take();           // 移除元素 - 队空阻塞

        // 第四组,限时阻塞
        queue.offer(4,1000, TimeUnit.SECONDS);   // 插入元素 - 超时false
        queue.poll(1000,TimeUnit.SECONDS);           // 移除元素 - 超时NULL
    }
}

欢迎疑问、期待评论、感谢指点 -- kiqi,愿同您为友

-- 星河有灿灿,愿与之辉

原文地址:https://www.cnblogs.com/kiqi/p/14394846.html