개발자 미니민의 개발스터디

[JAVA] 자바 - AtomicInteger 사용, BlockingQueue<E>

by mini_min
[JAVA]
자바 - AtomicInteger 사용, BlockingQueue<E>

✔️ AtomicInteger 란?

원자성을 보장하는 Integer 를 의미한다. 멀티 스레드 환경에서 동기화 문제를 별도의 synchronized 키워드 없이 안전하게 사용할 수 있다! (lock 도 없다 !)

 

📓 AtomicInteger 클래스 - Integer 값을 원자적으로 업데이트 하기 위한 클래스

📓 Atomic 이 붙으면 '원자적으로' 처리한다.

public class Ex01 {
	// private 붙여서 main 안에는 사용하지 않는다. 
	private static AtomicInteger count = new AtomicInteger(0);
	
	public static void main(String[] args) {
		for(int i=0; i<10; i++) {
			System.out.println(count.incrementAndGet()); //처음에 1반환
		}

	}

}

 

 

 

✔️ BlockingQueue 란?

BlockingQueue<E> 의 경우 Queue<E> 인터페이스를 상속 받은 인터페이스로, 해당 항목이 선입선출 순서로 저장되는 구조이다. Queue 는 멀티 스레드 환경에서 생산 및 소비의 구조에 필수적인 자료구조다.

 

✨ 자동으로 block 하는 기능이 있어 스레드에서 안전하다.

//생산자 클래스
	static class Producer implements Runnable {
		private BlockingQueue<String> queue;
		
		public Producer(BlockingQueue<String> queue) {
			this.queue = queue;
		}
		
		
		@Override
		public void run() {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			Date date = null;
			
			while(true) {
				date = new Date();
				
				try {
					queue.put(sdf.format(date)); // 큐에 현재 시간 추가
					// 큐 사이즈 출력
					
					System.out.printf("[%s] : size = %d\n", 
							Thread.currentThread().getName(), queue.size());
					
					Thread.sleep(200);
				} catch (InterruptedException e) {
				} 
				
			}
		}
		
	}
	
	
	// 소비자 클래스
	// queue 하나만 만들어서 생산자와 소비자 클래스에서 같이 사용하는 것?
	static class Consumer implements Runnable {
		private BlockingQueue<String> queue;
		
		public Consumer(BlockingQueue<String> queue) {
			this.queue = queue;
		}

		
		@Override
		public void run() {
			
			while(true) {
				try {
					System.out.printf("[%s] : %s\n", 
							Thread.currentThread().getName(), queue.take());
					
					Thread.sleep(1000);
					
				} catch (Exception e) {
				}
			}
			
		}
		
	}
💡 현재 스레드의 이름 가져오기 : Thread.currentThread().getName()

 

 

public static void main(String[] args) {
		//객체 하나만 생성함! main 쪽에서 ~~ 
		BlockingQueue<String> queue = new ArrayBlockingQueue<>(50); //큐 최대크기 50
		
		Thread p = new Thread(new Producer(queue));
		
		p.setName("생산자.."); // 스레드 이름 
		p.start();
		
		for(int i=0; i<5; i++) {
			Thread c = new Thread(new Consumer(queue));
			c.setName("소비자 " + (i+1));
			c.start();
			
		}
		

	}
💡 ArrayBlockingQueue<>(50) : 큐의 최대 크기를 50 준 것이다.
 : ArrayBlockingQueue 클래스는, 생성 후 크기 변경이 불가하다. 꽉 찼을 때 추가 block , 비었을 때 추출 block 상태가 된다. 

 

 

 

 

 

 

 

 

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기