多线程共享数据-非线程安全示例
发布日期:2022-04-11 08:52:53 浏览次数:20 分类:博客文章

本文共 1004 字,大约阅读时间需要 3 分钟。

多线程共享数据-非线程安全示例

package com.stono.thread2;import java.util.concurrent.atomic.AtomicInteger;public class Page11 extends Thread{    private int count = 5;    private AtomicInteger c2 = new AtomicInteger(5);    @Override    public void run() {        super.run();        // 此处会出现非线程安全问题        count --;        System.out.println("由 "+this.currentThread().getName()+" 计算, count= "+count);        // 这个线程安全        c2.decrementAndGet();        System.out.println("由 "+this.currentThread().getName()+" 计算, AtomicInteger= "+c2.get());    }    public static void main(String[] args) {        Page11 page11 = new Page11();        Thread a = new Thread(page11, "A");        Thread b = new Thread(page11, "B");        Thread c = new Thread(page11, "C");        Thread d = new Thread(page11, "D");        Thread e = new Thread(page11, "E");        a.start();        b.start();        c.start();        d.start();        e.start();            }}

使用AtomicInteger可以实现线程安全处理,但是输出顺序不是固定的;

 也可以在run()方法前面加上synchronized进行修饰;

 

转载地址:https://www.cnblogs.com/stono/p/8370621.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:多线程内存定位的命令总结
下一篇:多线程六 线程间的通信

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年03月27日 22时25分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章