Java AtomicInteger类的使用方法详解
首先看两段代码,一段是Integer的,一段是AtomicInteger的,为以下:
publicclassSample1{
privatestaticIntegercount=0;
synchronizedpublicstaticvoidincrement(){
count++;
}
}
以下是AtomicInteger的:
publicclassSample2{
privatestaticAtomicIntegercount=newAtomicInteger(0);
publicstaticvoidincrement(){
count.getAndIncrement();
}
}
以上两段代码,在使用Integer的时候,必须加上synchronized保证不会出现并发线程同时访问的情况,而在AtomicInteger中却不用加上synchronized,在这里AtomicInteger是提供原子操作的,下面就对这进行相应的介绍。
AtomicInteger介绍
AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。
AtomicInteger使用场景
AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用。
AtomicInteger源码部分讲解
publicclassAtomicIntegerextendsNumberimplementsjava.io.Serializable{
privatestaticfinallongserialVersionUID=6214790243416807050L;
//setuptouseUnsafe.compareAndSwapIntforupdates
privatestaticfinalUnsafeunsafe=Unsafe.getUnsafe();
privatestaticfinallongvalueOffset;
static{
try{
valueOffset=unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
}catch(Exceptionex){thrownewError(ex);}
}
privatevolatileintvalue;
以上为AtomicInteger中的部分源码,在这里说下其中的value,这里value使用了volatile关键字,volatile在这里可以做到的作用是使得多个线程可以共享变量,但是问题在于使用volatile将使得VM优化失去作用,导致效率较低,所以要在必要的时候使用,因此AtomicInteger类不要随意使用,要在使用场景下使用。
AtomicInteger实例使用
以下就是在多线程情况下,使用AtomicInteger的一个实例,这段代码是借用IT宅中的一段代码。
publicclassAtomicTest{
staticlongrandomTime(){
return(long)(Math.random()*1000);
}
publicstaticvoidmain(String[]args){
//阻塞队列,能容纳100个文件
finalBlockingQueuequeue=newLinkedBlockingQueue(100);
//线程池
finalExecutorServiceexec=Executors.newFixedThreadPool(5);
finalFileroot=newFile("D:\\ISO");
//完成标志
finalFileexitFile=newFile("");
//原子整型,读个数
//AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
finalAtomicIntegerrc=newAtomicInteger();
//原子整型,写个数
finalAtomicIntegerwc=newAtomicInteger();
//读线程
Runnableread=newRunnable(){
publicvoidrun(){
scanFile(root);
scanFile(exitFile);
}
publicvoidscanFile(Filefile){
if(file.isDirectory()){
File[]files=file.listFiles(newFileFilter(){
publicbooleanaccept(Filepathname){
returnpathname.isDirectory()||pathname.getPath().endsWith(".iso");
}
});
for(Fileone:files)
scanFile(one);
}else{
try{
//原子整型的incrementAndGet方法,以原子方式将当前值加1,返回更新的值
intindex=rc.incrementAndGet();
System.out.println("Read0:"+index+""+file.getPath());
//添加到阻塞队列中
queue.put(file);
}catch(InterruptedExceptione){
}
}
}
};
//submit方法提交一个Runnable任务用于执行,并返回一个表示该任务的Future。
exec.submit(read);
//四个写线程
for(intindex=0;index<4;index++){
//writethread
finalintnum=index;
Runnablewrite=newRunnable(){
StringthreadName="Write"+num;
publicvoidrun(){
while(true){
try{
Thread.sleep(randomTime());
//原子整型的incrementAndGet方法,以原子方式将当前值加1,返回更新的值
intindex=wc.incrementAndGet();
//获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
Filefile=queue.take();
//队列已经无对象
if(file==exitFile){
//再次添加"标志",以让其他线程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName+":"+index+""+file.getPath());
}catch(InterruptedExceptione){
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}
AtomicInteger使用总结
AtomicInteger是在使用非阻塞算法实现并发控制,在一些高并发程序中非常适合,但并不能每一种场景都适合,不同场景要使用使用不同的数值类。
以上就是本文关于JavaAtomicInteger类的使用方法详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:java原生序列化和Kryo序列化性能实例对比分析、关于Java企业级项目开发思想、Javamap存放数组并取出值代码详解等,有什么问题可以随时留言,小编会及时回复大家。