AtomicInteger的使用,重点是原子性,解决并发编程下的不一致问题,因为咱们都是程序猿,喜欢看代码,所以我就直接上代码说明问题了,还望各位小猿们支持:
实现一个计数器功能,下面用三种方式实现:
- 第一种,用一般的方式实现:
public class IntegerIncrement {
private static Integer count=0;
public static Integer increment(){
return ++count;
}
}
- 第二种,使用synchronized进行同步代码,保证不会出现并发线程同时访问的情况:
public class IntegerIncrement {
private static Integer count=0;
synchronized public static Integer increment(){
return ++count;
}
}
- 第三种,使用我这次提倡的AtomicInteger,这个是java1.4以后提供的并发编程的工具类,不仅保证了同步即原子性,而且效率比synchronized更高:
public class AtomicIntegerIncrement {
private static AtomicInteger count = new AtomicInteger(0);
synchronized public static Integer increment(){
return count.incrementAndGet();
}
}
接下来我们用多线程并发的情况去访问这个计数器功能,看看结果如何,让我们拭目以待哦!访问代码如下,我们创建了10000个线程去访问计数器,如果计数达到了10000,那么就会输出“good,计数器是对的哦,到达了10000”,如果没有达到就什么都不会输出:
public class Main {
public static void main(String[] args) {
for (int i =0; i < 10000; i++){
Thread thread = new Thread(){
@Override
public void run() {
if(IntegerIncrement.increment() == 10000){
System.out.println("good,计数器是对的哦,到达了10000");
}
}
};
thread.start();
}
}
}
下面打印上述三种的输出情况,答案就要揭晓了,是不是很激动呢?
- 第一种的输出结果:什么都没输出
- 第二种的输出结果:good,计数器是对的哦,到达了1000
- 第三种的输出结果:good,计数器是对的哦,到达了1000
结论:可以看到第一种存在并发访问的情况,第二种虽然解决了并发访问的情况,但是没有第三种方法的效率高,所以建议采取第三种方式!
下面再给一个多线程下使用AtomicInteger的实例,这段代码是借用别人的代码,稍作修改的,还请指教:
import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicTest {
static long randomTime() {
return (long) (Math.random() * 1000);
}
public static void main(String[] args) {
// 阻塞队列,能容纳100个文件
final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
// 线程池
final ExecutorService exec = Executors.newFixedThreadPool(5);
final File root = new File("F:\\data");
// 完成标志
final File exitFile = new File("");
// 原子整型,读个数
// AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
final AtomicInteger rc = new AtomicInteger();
// 原子整型,写个数
final AtomicInteger wc = new AtomicInteger();
// 读线程
Runnable read = new Runnable() {
public void run() {
scanFile(root);
scanFile(exitFile);
}
public void scanFile(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getPath().endsWith(".txt");
}
});
for (File one : files)
scanFile(one);
} else {
try {
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index = rc.incrementAndGet();
System.out.println("Read0: " + index + " " + file.getPath());
// 添加到阻塞队列中
queue.put(file);
} catch (InterruptedException e) {
}
}
}
};
exec.submit(read);
// submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
// 四个写线程
for (int index = 0; index < 4; index++) {
// write thread
final int num = index;
Runnable write = new Runnable() {
String threadName = "Write" + num;
public void run() {
while (true) {
try {
Thread.sleep(randomTime());
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index = wc.incrementAndGet();
// 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
File file = queue.take();
System.out.println("执行");
// 队列已经无对象
if (file == exitFile) {
// 再次添加"标志",以让其他线程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + ": " + index + " " + file.getPath());
} catch (InterruptedException e) {
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}
好了,今天就这样了,后面我会努力把concurrent下的所有的并发类都做介绍,还请大家支持支持哦!
版权声明:本文为zhaozhirongfree1111原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。