Java高并发程序-Chapter3 JDK并发包(第十八讲)同步控制之自定义SafeQueue

通过AtomicReference 实现 CAS 操作,完成无锁的SafeQueue

package com.john.learn.high.concurent.ch03.tools.support;

public class Node<T> {
	public Node prev;
	public Node next;
	public T item;
	
}
package com.john.learn.high.concurent.ch03.tools.support;

import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class SafeQueue<T> {

	private Node<T> head;

	private AtomicReference<Node> atomicReferenceTail = null;

	public SafeQueue() {

		this.head = new Node();

		atomicReferenceTail = new AtomicReference<Node>(this.head);
	}

	public void push(T item) {

		Node<T> node = new Node<T>();
		node.item = item;

		for (;;) {

			Node t = atomicReferenceTail.get();
			node.prev = t;

			// 线程安全
			if (atomicReferenceTail.compareAndSet(t, node)) {
				t.next = node;
				return;
			}
		}

	}

	// poll

	public T poll() {

		for (;;) {

			Node<T> tail = this.atomicReferenceTail.get();
			Node<T> prev = tail.prev;

			if (tail == this.head) {

				if (atomicReferenceTail.compareAndSet(tail, this.head)) {

					tail.prev = null;
				}

				return null;
			}

			if (atomicReferenceTail.compareAndSet(tail, prev)) {

				tail.next = null;

				return tail.item;
			}
		}

	}

	public Iterator<T> iterator() {

		return new Iterator<T>() {

			private Node<T> node = head;

			public boolean hasNext() {

				node = node.next;

				return node != null;
			}

			public T next() {

				return node.item;
			}

		};
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值