[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]AtomicInteger按范围滚动使用

上一篇:[备忘]postgresql报错:pg_dump报错:compressed data is corrupt
下一篇:[备忘]httpclient小备忘,setDefaultMaxPerRoute和通过代理超时,

添加日期:2022/5/23 10:03:32 快速返回   返回列表 阅读435次
需求:
希望AtomicInteger在1-10000之间循环使用,到10000了就从1重新开始。

找了一段代码,测试了一下,OK。
测试程序:


import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class TestAtomInteger {

    private final AtomicInteger i = new AtomicInteger(0);

    public static void main(String[] args) {
        final TestAtomInteger m = new TestAtomInteger();
        for (int t = 0; t < 10; t++) {
            Thread th = new Thread() {
                public void run() {
                    for (int i = 0; i < 20000; i++) {
                        System.out.println(Thread.currentThread().getName() + ":" + m.incrementAndGet());
                        try {
                            Thread.sleep(new Random().nextInt(5));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            th.setName("Thread " + t);
            th.start();

        }

    }

    public final int incrementAndGet() {
        int current;
        int next;
        do {
            current = this.i.get();
            next = current >= 10000 ? 1 : current + 1;
        } while (!this.i.compareAndSet(current, next));

        return next;
    }

    public final int decrementAndGet() {
        int current;
        int next;
        do {
            current = this.i.get();
            next = current <= 0 ? 10000 : current - 1;
        } while (!this.i.compareAndSet(current, next));

        return next;
    }
}

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved