文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java多线程 原子性操作类的使用

2024-04-02 19:55

关注

前言:

在java5以后,我们接触到了线程原子性操作,也就是在修改时我们只需要保证它的那个瞬间是安全的即可,经过相应的包装后可以再处理对象的并发修改,本文总结一下Atomic系列的类的使用方法,其中包含:

1. 基本类型的使用


public class AtomicTest {
    

    public static void main(String[] args) {

        final AtomicTicket ticket = new AtomicTicket();
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (ticket.getCount() > 0) {
                        System.out.println(Thread.currentThread().getName() + " count: " + ticket.decrement());
                    }
                }
            }).start();
        }
    }
}


class AtomicTicket {

    public AtomicInteger count = new AtomicInteger(100);

    public int decrement() {

        return count.getAndDecrement();
    }

    public int getCount() {
        return count.get();

    }
}

Thread-0 count: 100
Thread-2 count: 98
Thread-1 count: 99
Thread-2 count: 96
Thread-0 count: 97
Thread-2 count: 94
Thread-2 count: 92
Thread-1 count: 95
中间省略...
Thread-1 count: 12
Thread-2 count: 7
Thread-0 count: 9
Thread-2 count: 5
Thread-1 count: 6
Thread-2 count: 3
Thread-0 count: 4
Thread-2 count: 1
Thread-1 count: 2

2. 数组类型的使用


public class AtomicIntegerArrayTest {

    
    private final static AtomicIntegerArray ATOMIC_INTEGER_ARRAY = new AtomicIntegerArray(new int[]{1,2,3,4,5,6,7,8,9,10});

    public static void main(String []args) throws InterruptedException {
        Thread []threads = new Thread[10];
        for(int i = 0 ; i < 10 ; i++) {
            final int index = i;
            threads[i] = new Thread() {
                public void run() {
                    int original =  ATOMIC_INTEGER_ARRAY.get(index);
                    int result = ATOMIC_INTEGER_ARRAY.addAndGet(index, index + 1);
                    System.out.println("currentThread:" + Thread.currentThread().getName() + " , 原始值为:" + original + ",增加后的结果为:" + result);
                }
            };
            threads[i].start();
        }
        for(Thread thread : threads) {
            thread.join();
        }
        System.out.println("=========================>\n执行已经完成,结果列表:");
        for(int i = 0 ; i < ATOMIC_INTEGER_ARRAY.length() ; i++) {
            System.out.println(ATOMIC_INTEGER_ARRAY.get(i));
        }
    }
}

currentThread:Thread-0 , 原始值为:1,增加后的结果为:2
currentThread:Thread-3 , 原始值为:4,增加后的结果为:8
currentThread:Thread-2 , 原始值为:3,增加后的结果为:6
currentThread:Thread-1 , 原始值为:2,增加后的结果为:4
currentThread:Thread-5 , 原始值为:6,增加后的结果为:12
currentThread:Thread-4 , 原始值为:5,增加后的结果为:10
currentThread:Thread-6 , 原始值为:7,增加后的结果为:14
currentThread:Thread-7 , 原始值为:8,增加后的结果为:16
currentThread:Thread-8 , 原始值为:9,增加后的结果为:18
currentThread:Thread-9 , 原始值为:10,增加后的结果为:20
=========================>

执行已经完成,结果列表:
2
4
6
8
10
12
14
16
18
20

3. 引用类型的使用


public class AtomicReferenceTest {

    public static void main(String[] args) {
        People people1 =new People("Bom", 0);
        People people2 =new People("Tom",10);

        //先初始化一个值,如果不初始化则默认值为null
        AtomicReference<People> reference = new AtomicReference<>(people1);
        People people3 = reference.get();
        if (people3.equals(people1)) {
            System.out.println("people3:" + people3);
        } else {
            System.out.println("else:" + people3);
        }

        
        boolean b = reference.compareAndSet(null, people2);
        System.out.println("myClass.main-"+b+"--"+reference.get());

        boolean b1 = reference.compareAndSet(people1, people2);
        System.out.println("myClass.main-"+b1+"--"+reference.get());


        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());

                People people = reference.get();
                people.setName("Tom"+Thread.currentThread().getName());
                people.setAge(people.getAge()+1);
                reference.getAndSet(people);
                System.out.println(Thread.currentThread().getName()+reference.get().toString());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());

                People people = reference.get();
                people.setName("Tom"+Thread.currentThread().getName());
                people.setAge(people.getAge()+4);
                reference.getAndSet(people);
                System.out.println(Thread.currentThread().getName()+reference.get().toString());
            }
        }).start();

    }

}

 class People {
    private String name;
    private int age;

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}

4.字段类型的使用


public class AtomicIntegerFieldUpdaterTest {

    
    public final static AtomicIntegerFieldUpdater<A> ATOMIC_INTEGER_UPDATER = AtomicIntegerFieldUpdater.newUpdater(A.class, "intValue");

    public static void main(String[] args) {
        final A a = new A();
        for (int i = 0; i < 10; i++) {

            new Thread() {
                public void run() {
                    System.out.println(
                            Thread.currentThread().getName() + " " + ATOMIC_INTEGER_UPDATER.get(a));
                    ATOMIC_INTEGER_UPDATER.addAndGet(a, 11);
                    System.out.println(
                            Thread.currentThread().getName() + " " + ATOMIC_INTEGER_UPDATER.get(a));
                    if (ATOMIC_INTEGER_UPDATER.compareAndSet(a, ATOMIC_INTEGER_UPDATER.get(a), 120)) {
                        System.out.println(Thread.currentThread().getName() + " 对应的值做了修改!");
                    }
                    System.out.println(
                            Thread.currentThread().getName() + " " + ATOMIC_INTEGER_UPDATER.get(a));
                }
            }.start();
        }
    }

    static class A {
        volatile int intValue = 100;
    }
}

Thread-0 100
Thread-2 100
Thread-1 100
Thread-2 122
Thread-3 111
Thread-5 120
Thread-0 111
Thread-5 142
Thread-3 131
Thread-2 对应的值做了修改!
Thread-2 120
Thread-8 120
Thread-4 133
Thread-1 133
Thread-9 142
Thread-4 142
Thread-4 对应的值做了修改!
Thread-8 131
Thread-3 对应的值做了修改!
Thread-3 120
Thread-7 120
Thread-7 131
Thread-5 对应的值做了修改!
Thread-5 120
Thread-6 120
Thread-0 对应的值做了修改!
Thread-6 131
Thread-7 对应的值做了修改!
Thread-8 对应的值做了修改!
Thread-4 120
Thread-9 131
Thread-1 对应的值做了修改!
Thread-9 对应的值做了修改!
Thread-8 120
Thread-7 120
Thread-6 对应的值做了修改!
Thread-0 131
Thread-6 120
Thread-9 120
Thread-1 120

到此这篇关于Java多线程 原子性操作类的使用的文章就介绍到这了,更多相关Java多线程 原子性操作类内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯