[심화] 10. 푸쉬

백하림's avatar
Jul 25, 2025
[심화] 10. 푸쉬

Customer.java

package ex08.push.sub; public interface Customer { void update(String msg); }

Cu1.java

package ex08.push.sub; public class Cus1 implements Customer { @Override public void update(String msg) { System.out.println("손님1이 받은 알림 : " + msg); } }

Cus2.java

package ex08.push.sub; public class Cus2 implements Customer { @Override public void update(String msg) { System.out.println("손님2이 받은 알림 : " + msg); } }

Mart.java

package ex08.push.pub; import ex08.push.sub.Customer; public interface Mart { // Publisher // 1. 구독 void add(Customer customer); // 2. 구독 취소 void remove(Customer customer); // 3. 출판 void received(); // 4. 알림 void notify(String msg); }

LotteMart.java

package ex08.push.pub; import ex08.push.sub.Customer; import java.util.ArrayList; import java.util.List; public class LotteMart implements Mart { // 구독자 리스트 private List<Customer> customerList = new ArrayList<>(); // 구독 등록 @Override public void add(Customer customer) { customerList.add(customer); } // 구독 취소 @Override public void remove(Customer customer) { customerList.remove(customer); } // 출판 @Override public void received() { for (int i = 0; i < 5; i++) { System.out.println("."); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } notify("LotteMart : 바나나"); // 콜백 메서드 } @Override public void notify(String msg) { for (Customer customer : customerList) { customer.update(msg); } } }

EMart.java

package ex08.push.pub; import ex08.push.sub.Customer; import java.util.ArrayList; import java.util.List; public class EMart implements Mart { // 구독자 리스트 private List<Customer> customerList = new ArrayList<>(); // 구독 등록 @Override public void add(Customer customer) { customerList.add(customer); } // 구독 취소 @Override public void remove(Customer customer) { customerList.remove(customer); } // 출판 @Override public void received() { for (int i = 0; i < 5; i++) { System.out.println("."); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } notify("EMart : 딸기"); // 콜백 메서드 } @Override public void notify(String msg) { for (Customer customer : customerList) { customer.update(msg); } } }

App.java

package ex08.push; import ex08.push.pub.EMart; import ex08.push.pub.LotteMart; import ex08.push.sub.Cus1; import ex08.push.sub.Cus2; public class App { public static void main(String[] args) { // 1. 객체 초기화 LotteMart lotteMart = new LotteMart(); EMart emart = new EMart(); Cus1 cus1 = new Cus1(); Cus2 cus2 = new Cus2(); // 2. 구독 lotteMart.add(cus1); lotteMart.add(cus2); emart.add(cus1); emart.add(cus2); // 3. 구독 취소 lotteMart.remove(cus2); // 4. 출판 (누가 할 지는 나중에 정하면 됨) new Thread(() -> { lotteMart.received(); }).start(); new Thread(() -> { emart.received(); }).start(); } }
notion image

Thread를 2개 만든 이유

🔥
즉, 입고 대기 시간 중복 없이 동시 처리하려고 Thread를 사용한 것.
Share article

harimmon