Java 并发原子操作类(转)
转自:https://www.jianshu.com/p/3632a0f9f083
线程不安全的高并发实现
客户端模拟执行 5000 个任务,线程数量是 200,每个线程执行一次,就将 count 计数加 1,当执行完以后,打印 count 的值。
package atomic;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import annotation.NotThreadSafe;
@NotThreadSafe
public class NotThreadSafeConcurrency {
private static int CLIENT_COUNT = 5000;
private static int THREAD_COUNT = 200;
private static int count = 0;
private static int[] values = new int[11];
private static ExecutorService executorService = Executors.newCachedThreadPool();
private final static Semaphore semaphore = new Semaphore(THREAD_COUNT);
private final static CountDownLatch countDownLatch = new CountDownLatch(CLIENT_COUNT);
public static void main(String[] args) throws Exception {
testAtomicInt();
}
private static void testAtomicInt() throws Exception {
for (int i = 0; i < CLIENT_COUNT; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
// count每加 1,进行减 1 计数
countDownLatch.countDown();
});
}
// 等待线程池所有任务执行结束
countDownLatch.await();
executorService.shutdown();
System.out.println("ConcurrencyDemo:" + count);
}
private static void add() {
count++;
}
}
//----------------------------------执行结果-------------------------------------------
由于是非线程安全的,所以运行结果总是 <= 5000
ConcurrencyDemo:5000
ConcurrencyDemo:4999
ConcurrencyDemo:4991
ConcurrencyDemo: