간단 한 압력 측정 시 뮬 레이 션

1962 단어 자바압력 측정
더 읽 기

import java.time.Duration;
import java.time.LocalDateTime;
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;

public class CountExample {
	
	private static final int clientTotal = 5000;
	
	private static final int threadTotal = 8;
	
	private static AtomicInteger count = new AtomicInteger(0);
	
	public static void main(String... args) {
		
		ExecutorService executorService = Executors.newFixedThreadPool(threadTotal);
		final CountDownLatch latch = new CountDownLatch(clientTotal);
		final Semaphore semaphore = new Semaphore(threadTotal);
		LocalDateTime start = LocalDateTime.now();
		for (int i = 0; i < clientTotal; i++) {
			
			executorService.execute(() -> {
				
				try {
					
					semaphore.acquire();
					add();
					System.out.println(String.format("add() invoked by %s => %d", Thread.currentThread().getName(), count.get()));
					semaphore.release();
					latch.countDown();
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			});
		}
		try {
			
			latch.await();
			LocalDateTime end = LocalDateTime.now();
			System.out.println(String.format("cost time millis : %d", Duration.between(start, end).toMillis()));
			executorService.shutdown();
			System.out.println(String.format("count:%d", count.intValue()));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void add() {
		
		count.getAndIncrement();
	}
}


좋은 웹페이지 즐겨찾기