最近开始研究并发的问题,今天找了段代码,是在并发环境共享变量的不安全问题,如下所示:
public class ConcurrentTest { //1000个请求 private static int quest_count = 1000; //同时允许50个请求运行 private static int concurrent_count = 50; private static int count = 0; public static void main(String[] args) throws Exception{ ExecutorService executor = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(concurrent_count);//信号量 final CountDownLatch countDownLatch = new CountDownLatch(quest_count);// for (int i = 0; i < quest_count; i++){ executor.execute(new Runnable() { @Override public void run() { try { semaphore.acquire(); add(); semaphore.release(); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } countDownLatch.await(); executor.shutdown(); System.out.printf("count:"+count); } private static void add(){ count++; } }
我创建了一个线程池,是cachedThreadPool,最大支持Integer.MAX_VALUE个线程,具体实现代码如下:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
之后再详细说线程池。继续上面的代码,我在主线程中通过for循环创建了1000个请求,最多同时允许50个线程运行,每个线程做累加操作,最后打印count结果。
结果如下所示:count:947、count:938、count:876 结果都不是1000,显而易见的。
原因分析:A线程从主内存中获取到变量count放置在自己线程私有线程栈中,对count做+1操作 count =1,B线程同时从主存中获取count(count=0)放置在线程B的栈中,对count做+1操作,之后B和A如果都将count写回主存,count还是1,我们期望值应该是2。另外++操作在cpu中会拆成三条指令,取值、自增、赋值,并不是原子的,也会有风险。
改造:
方案1:使用AtomicInteger
代码如下:
public class ConcurrentTest { //1000个请求 private static int quest_count = 1000; //同时允许50个请求运行 private static int concurrent_count = 50; private static AtomicInteger count = new AtomicInteger(0); public static void main(String[] args) throws Exception{ ExecutorService executor = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(concurrent_count);//信号量 final CountDownLatch countDownLatch = new CountDownLatch(quest_count);// for (int i = 0; i < quest_count; i++){ executor.execute(new Runnable() { @Override public void run() { try { semaphore.acquire(); add(); semaphore.release(); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } countDownLatch.await(); executor.shutdown(); System.out.printf("count:"+count); } private static void add(){ count.incrementAndGet(); } }
执行结果:count:1000
下一篇文章分析AtomicInteger为什么在多线程下共享变量安全。