多线程安全之automic

import java.util.concurrent.atomic.AtomicInteger;

/**

  • volatile不具备synchronized关键字的原子性(同步)

  • AtomicInteger具备原子性(同步)
    */
    public class VolatileNoAtomic extends Thread{
    //private static volatile int count;
    private static AtomicInteger count = new AtomicInteger(0);
    private static void addCount(){
    for (int i = 0; i < 1000; i++) {
    //count++ ;
    count.incrementAndGet();
    }
    System.out.println(count);//打印会有延迟,最终结果是10000
    }

    public void run(){
    addCount();
    }

    public static void main(String[] args) {

     VolatileNoAtomic[] arr = new VolatileNoAtomic[100];
     for (int i = 0; i < 10; i++) {
         arr[i] = new VolatileNoAtomic();
     }
    
     for (int i = 0; i < 10; i++) {
         arr[i].start();
     }
    

    }
    }

/**

  • 多个AtomicInteger的方法执行不具备原子性(一个方法有原子性)
  • @author Administrator

*/
public class AtomicUse {
private static AtomicInteger count = new AtomicInteger(0);
//多个addAndGet在一个方法内是非原子性的,需要加synchronized进行修饰,保证4个addAndGet整体原子性
/*synchronized/
public synchronized int multiAdd(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.addAndGet(1);
count.addAndGet(2);
count.addAndGet(3);
count.addAndGet(4); //+10
return count.get();
}

public static void main(String[] args) {
    final AtomicUse au = new AtomicUse();

    List<Thread> ts = new ArrayList<Thread>();
    for (int i = 0; i < 100; i++) {
        ts.add(new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(au.multiAdd());
            }
        }));
    }

    for(Thread t : ts){
        t.start();
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值