int a = 1;
boolean flag = true;
假如不是a = 1的操作,而是a = new byte[1024*1024](分配1M空间),那么它会运行地很慢,此时CPU是等待其执行结束呢,还是先执行下面的语句flag=true呢?显然,先执行flag=true可以提前使用CPU,加快整体效率,当然这样的前提是不会产生错误。
/**
* Returns the number of keys in this hashtable.
*
* @return the number of keys in this hashtable.
*/
public synchronized int size() {
return count;
}
/**
* Tests if this hashtable maps no keys to values.
*
* @return <code>true</code> if this hashtable maps no keys to values;
* <code>false</code> otherwise.
*/
public synchronized boolean isEmpty() {
return count == 0;
}
HashTable的所有函数都是用synchronized,用的同一把锁,就是当前的HashTable对象,可想而知它的效率能高到哪儿去。
(2) JDK中的ConcurrentHashMap
/**
* Stripped-down version of helper class used in previous version,
* declared for the sake of serialization compatibility
*/
static class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
final float loadFactor;
Segment(float lf) { this.loadFactor = lf; }
}
ConcurrentHashMap中的分段锁称为Segment,它即类似于HashMap(JDK7与JDK8中HashMap的实现)的结构,即内部拥有一个Entry数组,数组中的每个元素又是一个链表;同时又是一个ReentrantLock(Segment继承了ReentrantLock)。
当需要put元素的时候,并不是对整个hashmap进行加锁,而是先通过hashcode来知道他要放在那一个分段中,然后对这个分段进行加锁,所以当多线程put的时候,只要不是放在一个分段中,就实现了真正的并行的插入。
public void increase() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " i want know current i = " + i);
i++;
System.out.println(Thread.currentThread().getName() + " after increase i = " + i);
}
}
}
public static void main(String[] args) {
final TestSynchronized testSynchronized = new TestSynchronized();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
testSynchronized.increase();
}
}, "thread - " + i).start();
}
}
这个时候,拿i的值也是需要加锁的。
执行输出:
thread - 0 i want know current i = 0
thread - 0 after increase i = 1
thread - 4 i want know current i = 1
thread - 4 after increase i = 2
thread - 3 i want know current i = 2
thread - 3 after increase i = 3
thread - 2 i want know current i = 3
thread - 2 after increase i = 4
thread - 1 i want know current i = 4
thread - 1 after increase i = 5