多线程情况下保证数据一致的方法

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class loadNum {

private static int num = 0;

1、使用synchronized关键字
private static synchronized void increment1() {
num++;
}

2、使用Lock锁
private static Lock lock = new ReentrantLock();
public static void increment2() {
lock.lock();
num++;
lock.unlock();
}

3、使用Atomic原子类
private static AtomicInteger ai = new AtomicInteger();

public static void increment3() {

    num= ai.getAndIncrement();


}


public static void main(String[] args) {
    long time1 = new Date().getTime();
    for(int i=0;i<10;i++) {
        new Thread(new Runnable() {
            public void run() {
                // TODO Auto-generated method stub
                for(int j=0;j<10000;j++) {
                    increment3();
                }
            }
        }).start();
    }

    //确保所有线程调用完毕
    while(Thread.activeCount()>2)
        Thread.currentThread().getThreadGroup().list();
        Thread.yield(); //继续执行此线程
    System.out.println(num);
    System.out.println("time="+(new Date().getTime()-time1)); //执行所用时间
}

}

你可能感兴趣的:(java,并发编程)