演示并发场景下代码问题

【前言】
不安全的并发线程使用,导致最后结果,与期望不一致。
【正文】
200个线程执行5000次任务,得到的结果是不确定的(4921 4851 4453),现在的实现方式,是不安全的。将线程数改为1,每次得到的结果都是5000.

public class ConutThread {

	//線程數
	private static int threadTotal = 200;
	//任務數
	private static int clientTotal = 5000;
	//標誌位
	private static long count = 0;
	
	public static void main(String[] args) {
		//啟動線程池
		ExecutorService exec = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(threadTotal);
		for (int i = 0; i < clientTotal; i++) {
			exec.execute(() -> {
				try {
					//調用線程
					semaphore.acquire();
					count++;
					//釋放線程
					semaphore.release();
					} 
				catch (Exception e) {
					}
			});			
		}
		//關閉線程池
		exec.shutdown();
		//輸出標誌位
		System.out.println(count);
	}
}
posted @ 2018-04-30 21:40  李凯伦  阅读(136)  评论(0)    收藏  举报