10048--- AtomicInteger的介绍和使用
来源:互联网 发布:把mac里的文件拷到u盘 编辑:程序博客网 时间:2024/06/05 23:03
原文
1、类介绍
可以用原子方式更新的 int 值。
2、使用场景
主要用于在高并发环境下的高效程序处理。使用非阻塞算法来实现并发控制。
3、相关实例
在并发情况下使用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("D:\\ISO"); // 完成标志 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(".iso"); } }); 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) { } } } }; // submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。 exec.submit(read); // 四个写线程 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(); // 队列已经无对象 if (file == exitFile) { // 再次添加"标志",以让其他线程正常退出 queue.put(exitFile); break; } System.out.println(threadName + ": " + index + " " + file.getPath()); } catch (InterruptedException e) { } } } }; exec.submit(write); } exec.shutdown(); }}
0 0
- 10048--- AtomicInteger的介绍和使用
- AtomicInteger的介绍和使用
- AtomicInteger的介绍和使用
- AtomicInteger的介绍和使用
- JAVA 中无锁的线程安全整数 AtomicInteger介绍和使用
- JAVA中无锁的线程安全整数AtomicInteger介绍和使用
- AtomicInteger的介绍
- AtomicInteger理解和使用
- AtomicInteger原子的使用
- AtomicInteger的使用
- AtomicInteger的使用
- 无锁类的使用---AtomicInteger
- AtomicInteger介绍
- AtomicInteger介绍
- AtomicInteger介绍
- AtomicInteger介绍
- AtomicInteger介绍
- Java中AtomicInteger的使用!!!
- 最长递增子序列的O(NlogN)算法
- request取不到post请求过来的参数
- AFNetworking 批量上传统一返回图片的3种方法
- 二叉树
- HDU 2050 折线分平面
- 10048--- AtomicInteger的介绍和使用
- 数据库事务ACID
- HDU 2222 Keywords Search AC自动机
- 使用Jsoup爬网页出现500错误
- 查找算法
- webrtc 音频VAD 检测
- HDU 2896 病毒侵袭 AC自动机
- Java StringBuffer和StringBuilder类
- 记一次前段调试问题