多线程是面试必被问,而且问的很深的东西啊
关于原子类,也会问到。
Random中的seed是用的原子类,因此是线程安全的。但是效率不高。
来看看AtomicLong的实现
因为java的slot只有32位,而long和double是64位的,因此不是原子类
因此java中定义了AtomicLong,来实现原子的long类型。
举个栗子
private static AtomicBoolean INITED = new AtomicBoolean(false);
public static void init(Context context) {
if ( INITED.compareAndSet( false,true ) ) {
initialize();
}
}
package java.util.concurrent.atomic;
AtomicLong extends Number implements Serializable{
static final Unsafe unsafe = Unsafe.getUnsafe();
static final long valueOffset;
检查JVM是否支持lockless comparenAndSwap for longs
static final VM_SUPPORT_LONG_CAS = VMSupportCS8()这是一个native方法
static {
try{
valueOffset = unsafe.objectFieldOffset(AtomicLong.class.getDeclaredFile("value"));
}catch(Exception ex){}
}
private volatile long value;
AtomicLong(long initialValue){
value = initialValue;
}
AtomicLong(){
}
public final long get(){
return value;
}
public final void set(long newValue){
value = newValue;
}
public final void lazySet(long newValue){
unsafe.putOrderedLong(this,valueOffset,newValue);
}
原子方法,将newValue设置进去,同时返回旧值
public final long getAndSet(long newValue){
while(true){
long current = get();
if (compareAndSet(current,newValue))
return current;
}
}
如果当前值等于expect,将其设置为update值
public final boolean compareAndSet(long expect, long update){
return unsafe.compareAndSwapLong(this,valueOffset,expect,update);
}
public final boolean weakCompareAndSet(long expect, long update){
return unsafe.compareAndSwapLong(this,valueOffset,expect,update);
}
原子操作,自增1。循环执行?
public final long getAndIncrement(){
while(true){
long current = get();
long next = current +1;
if(compareAndSet(current,next));
return current;
}
}
原子操作
public final long getAndDecrement(){
while(true){
long current = next();
long next = current - 1;
if(compareAndSet(current,next))
return current;
}
}
原子操作
public final long getAndAdd(long delta){
while(true){
long current = get();
long next = current +delta;
if(compareAndSet(current,next))
return current;
}
}
原子操作
public final long incrementAndGet(){
for(;;){
long current = get();
long next = current +1;
if(compareAndSet(current,next))
return next;
}
}
原子操作,自减1并返回当前值
public final long decrementAndGet(){
for(;;){
long current = get();
long next = current -1;
if(compareAndSet(current,next))
return next;
}
}
public final long addAndGet(long delta){
for(;;){
long current = get();
long next = current + delta;
}
if(compareAndSet(current,next))
return next;
}
}
public String toString(){
return Long.toString(get());
}
public int intValue(){
return (int)get();
}
public long longValue(){
return (float)get();
}
public float floatValue(){
return (float)get();
}
public double doubleValue(){
return (double)get();
}
// TO Be Continued
// Done!!!