public class Counter {
private volatile int a = 0;
public synchronized int incrAndGet(int number) {
this.a += number;
return a;
}
public synchronized int get() {
return a;
}
}
public synchronized int compareAndSwap(int expect, int newValue) {
int old = this.a;
if (old == expect) {
this.a = newValue;
}
return old;
}
private volatile int value;
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
package concurrenttest;
import java.util.concurrent.atomic.AtomicReference;
public class ConcurrentStack<e> {
AtomicReference<node<e>> top = new AtomicReference<node<e>>();
public void push(E item) {
Node<e> newHead = new Node<e>(item);
Node<e> oldHead;
while (true) {
oldHead = top.get();
newHead.next = oldHead;
if (top.compareAndSet(oldHead, newHead)) {
return;
}
}
}
public E pop() {
while (true) {
Node<e> oldHead = top.get();
if (oldHead == null) {
return null;
}
Node<e> newHead = oldHead.next;
if (top.compareAndSet(oldHead, newHead)) {
return oldHead.item;
}
}
}
private static class Node<e> {
public final E item;
public Node<e> next;
public Node(E item) {
this.item = item;
}
}
}
public boolean offer(E e) {
checkNotNull(e);
final Node<e> newNode = new Node<e>(e);
for (Node<e> t = tail, p = t;;) {
Node<e> q = p.next;
if (q == null) {
// p is last node
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有