Java多线程编程

全部教程

×

Java原子类自增自减操作

我们知道i++操作不是原子操作, 除了使用Synchronized进行同步外,也可以使用AtomicInteger/AtomicLong原子类进行实现。

package com.wkcto.volatilekw;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 使用原子类进行自增
 * Author: 老崔
 */
public class Test04 {
    public static void main(String[] args) throws InterruptedException {
        //在main线程中创建10个子线程
        for (int i = 0; i < 1000; i++) {
            new MyThread().start();
        }
        Thread.sleep(1000);
        System.out.println( MyThread.count.get());
    }

    static class MyThread extends Thread{
       //使用AtomicInteger对象
        private static AtomicInteger count = new AtomicInteger();

        public  static void addCount(){
            for (int i = 0; i < 10000; i++) {
                //自增的后缀形式
                count.getAndIncrement();
            }
            System.out.println(Thread.currentThread().getName() + " count=" + count.get());
        }

        @Override
        public void run() {
            addCount();
        }
    }
}

 

技术文档推荐

更多>>

视频教程推荐

更多>>