package cn.xing Zhiwei.com mon.thread;
importorg.spring framework.util.stopwatch;
//*
*同步IED悲观锁定
*/
publicclassthreadextendstestextendsthread {
privatevolatilestaticintegernum=0;
公共静态语音打印(
system.out.println(num;
}
@Override
公共语音运行(}
//string name=thread.current thread ().getName );
for(intI=0; i10; I ) {
同步(this ) {
num=i;
}
//system.out.print ln (name ' : ' I );
}
}
//*
* i执行时间(秒) num执行结果
* i100 0.017 4500
* i1000 0.125 45000
* i10000 1.61 450000
* i100000 10.812 4500000
*
* @param args
* @throws InterruptedException
*/
publicstaticvoidmain (string [ ] args ) throws InterruptedException {。
StopWatch clock=new StopWatch (;
clock.start (;
for(intI=0; i100; I ) {
threadextendstestthread=newthreadextendstest (;
thread.start (;
thread.join (;
}
clock.stop (;
system.out.println (clock.gettotaltimeseconds () );
ThreadExtendsTest.print (;
}
}
package cn.xing Zhiwei.com mon.thread;
importorg.spring framework.util.stopwatch;
import java.util.Date;
import Java.util.concurrent.atomic.atomicstampedreference;
//*
*自动乐观摇滚
*/
publicclassoptlockthreadtestextendsthread {
privatevolatilestaticatomicstampedreferencesum=newatomicstampedreference (0,new Date ).toInstant ).getNano );
@Override
公共语音运行(}
//string name=thread.current thread ().getName );
for(intI=0; i10; I ) {
Integer m=sum.getReference (;
m=i;
boolean is=sum.compareandset (sum.get reference )、m、sum.getStamp )、new Date ).toInstant ).getNano ) ) )。
if (! is ) {
System.out.println ('叠加失败');
}
//system.out.print ln (name ' : ' I );
}
}
//*
* i执行时间(秒) num执行结果
* i100 0.022 4500
* i1000 0.137 45000
* i10000 1.378 450000
* i100000 10.638 4500000
*
* @param args
* @throws InterruptedException
*/
publicstaticvoidmain (string [ ] args ) throws InterruptedException {。
StopWatch clock=new StopWatch (;
clock.start (;
for(intI=0; i100000; I ) {
optlockthreadtestthread=newoptlockthreadtest (;
thread.start (;
thread.join (;
}
clock.stop (;
system.out.println (clock.gettotaltimeseconds () );
system.out.println (sum.get reference () );
}
}
通过实际测试
测试背景显示,在没有错误的情况下运行,或者没有发生自动旋转锁定,导致重复等待
atomic实现与同步基本相同。 想想为什么。 乐观锁定的实现可能是因为使用了cpu的锁定。
cpu的锁分为:
处理器保证存储器操作的原子性
总线锁定(多处理器) )
高速缓存锁定
我现在有一个问题。 如果这两种实现方法和执行结果相同,为什么会出现乐观锁这个concurrent? 是为了解决什么问题?
Java通过JDK1.5提供了java.util.concurrent.atomic包,使程序员可以在多线程环境中执行原子操作而无需锁定。 虽然原子变量的基础是处理器提供的原子指令,但这种方法绝对不能保证线程不会被阻塞,因为不同的CPU体系结构提供的原子指令可能不同,或者可能需要某种形式的内部锁定。
如果只是提倡的话,这种方式到底有什么方便呢?
只做测试,如果有什么不对的地方呢? 请用信息告诉我