java多线程学习(二)

1.在java中,提供了许多同步容器,包括Vector,Hashtable,以及Collections.synchronizedSet,synchronizedList等,但同步容器将所有的容器状态访问串行化,降低了性能。在java5.0之后,又出现了一批并发容器。

对线程的保护,用的是加锁的方式,而并发容器选择了分段锁。

 从java的源代码来看,可以比较清楚。

View Code
/*jdk 1.7 ConcurrentHashMap put*/
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
            HashEntry<K,V> node = tryLock() ? null :
                scanAndLockForPut(key, hash, value);
            V oldValue;
            try {
                HashEntry<K,V>[] tab = table;
                int index = (tab.length - 1) & hash;
                HashEntry<K,V> first = entryAt(tab, index);
                for (HashEntry<K,V> e = first;;) {
                    if (e != null) {
                        K k;
                        if ((k = e.key) == key ||
                            (e.hash == hash && key.equals(k))) {
                            oldValue = e.value;
                            if (!onlyIfAbsent) {
                                e.value = value;
                                ++modCount;
                            }
                            break;
                        }
                        e = e.next;
                    }
                    else {
                        if (node != null)
                            node.setNext(first);
                        else
                            node = new HashEntry<K,V>(hash, key, value, first);
                        int c = count + 1;
                        if (c > threshold && tab.length < MAXIMUM_CAPACITY)
                            rehash(node);
                        else
                            setEntryAt(tab, index, node);
                        ++modCount;
                        count = c;
                        oldValue = null;
                        break;
                    }
                }
            } finally {
                unlock();
            }
            return oldValue;
        }

ConcurrentHashMap返回的迭代器保证了弱一致性的特点,即可以在迭代器被构造后将修改操作反映给容器。在java源代码中也提到了“The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.”

2. java6中还有双端队列的容器,它们支持一种“work stealing”的模式,能够降低生产-消费模式中对共享工作队列 的竞争访问。“work stealing”适合既是生产者又是消费者的工作线程,由自己维护独立的工作队列,并且当自己的任务完成后,从另一个工作线程中“steal”新的任务。  

3.同步工具类

闭锁:CountDownLatch

FutureTask:表示一种抽象的可生成结果的计算。FutureTask.get会阻塞直到任务进入完成状态。

Semaphore

posted @ 2013-05-07 22:23  ChinaInterLude  阅读(175)  评论(0)    收藏  举报