并发库学习笔记三

来源:互联网 发布:磊科 网络尖兵配置 编辑:程序博客网 时间:2024/06/05 16:02

Synchronized lock的一种简化实现,一个lock可以应对多个condition

synchronizedlockcondiiton合并了,一个synchronized Lock

只对应一个condition jdk中他们的效率差不多

注:不要在lockcondition上使用wait notify  notifyAll方法

使用AtomicInteger

class Counter {

private volatile int count = 0;

// 若要线程安全执行count++,需要加锁

public synchronized void increment() {

count++;

}

public int getCount() {

return count;

}

}

class Counter2 {

private AtomicInteger count = new AtomicInteger();

       

//使用AtomicInteger后,不需要加锁,也可以实现线安全

public void increment() {

count.incrementAndGet();

}

public int getCount() {

return count.get();

}

}

这是硬件提供原子操作指令实现的,其他的原子操作还有

 AtomicBoolean       AtomicLong    AtomicReference<T>

使用Lock-Free算法

 class Counter {

private volatile int max = 0;

// 若要线程安全执行count++,需要加锁

public synchronized void set(int value) {

if (value > max) {

max = value;

}

}

public int getMax() {

return max;

}

}

class Counter2 {

private AtomicInteger max = new AtomicInteger();

// 使用AtomicInteger后,不需要加锁,也可以实现线安全

public void set(int value) {

for (;;) {

int current = max.get();

if (value > current) {

if (max.compareAndSet(current, value)) {

break;

else {

continue;

}

else {

break;

}

}

}

public int getCount() {

return max.get();

}

}

Lock-Free的数据结构

class BeanManager {

private Map<String, Object> map = new HashMap<String, Object>();

public Object getBeans(String key) {

synchronized (map) {

Object bean = map.get(key);

if (bean == null) {

map.put(key, createBean());

bean = map.get(key);

}

return bean;

}

}

}

class BeanManager2 {

private ConcurrentMap<String, Object> map = new ConcurrentHashMap<String, Object>();

public Object getBeans(String key) {

Object bean = map.get(key);

if (bean == null) {

map.putIfAbsent(key, createBean());

bean = map.get(key);

}

return bean;

}

}

原创粉丝点击