본문 바로가기
혼자서 개발새발

JAVA) 멀티쓰레드를 이용해 영화관에서 티켓을 팔자!

by 휴일이 2022. 10. 20.

 

멀티쓰레드를 이용해서

영화관 티켓을 파는 코드를 만들어 보았다ㅎㅎ

 

 

 

먼저 티켓을 팔고 채우는 티켓 클래스!

 

package ThreadStudyCGV;

import java.util.ArrayList;

public class Ticket {

    final int MAX_TICKET=3;
    final String ticket = "ticket";
    ArrayList<String> ticketBox = new ArrayList<String>();

    Ticket() {}

    public synchronized void add()  {
        String name = Thread.currentThread().getName(); //직원 이름 부여
        while(true) {
            ticketBox.add(ticket); //무한 티켓 추가
            if(ticketBox.size()>=MAX_TICKET) { //티켓이 꽉 차면
                notifyAll(); //잠자는 손님을 깨운다!
                System.out.println(name+"이 티켓을 채웠습니다"); //티켓이 꽉 찼다고 알려준다
                try {
                    wait(); //찼으면 기다린다
                    Thread.sleep(500); //메모리 비우기 위해 조금 재운다
                } catch(Exception e) {}
            }
        }
    }

    public synchronized void buy() {
        String name = Thread.currentThread().getName(); //손님 이름을 얻기 위해!
        if(ticketBox.size()<=0) { //티켓이 0이 되면
            System.out.println("티켓이 없어요"); //티켓없다고 알려준다
            try {
                wait(); //티켓이 찰 때까지 재운다
                Thread.sleep(50); //재가동 할 때 메모리 비워주기
            } catch(Exception e) {}

        } else {
            for(int i=0;i<ticketBox.size();i++) { //티켓이 0이 아니라면
                ticketBox.remove(i); //티켓을 1장 판매하고(지우고)
                System.out.println(name+"님 즐거운 관람 되세요 :)"); //인사를 한다!
            }
        } notifyAll(); //직원(사실 모두)를 깨운다
    }

}

 

 

 

CGV(직원) 클래스

package ThreadStudyCGV;

public class CGV implements Runnable {

    private Ticket ticket;
    CGV(Ticket ticket) {
        this.ticket = ticket;

    }

    @Override
    public void run() {
        while(true) {
            ticket.add(); //티켓 채우기
            try {
                Thread.sleep(100); //0.1초 쉬기
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

 

손님 클래스

package ThreadStudyCGV;

public class Guest implements Runnable {

    private Ticket ticket;

    Guest(Ticket ticket) {
        this.ticket = ticket;
    }

    @Override
    public void run() {
        while(true) {
            ticket.buy(); //티켓사기
            try{
                Thread.sleep(100); //0.1초 쉬기
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

 

 

메인 클래스

package ThreadStudyCGV;


public class TestMovie {
    public static void main(String[] args) throws InterruptedException {

        Ticket ticket = new Ticket();
        new Thread(new CGV(ticket), "CGV 직원").start();
        new Thread(new Guest(ticket), "휴일").start(); //손님1
        new Thread(new Guest(ticket), "사랑").start(); //손님2
        new Thread(new Guest(ticket), "도롱이").start(); //손님3
        Thread.sleep(3000);
        System.exit(0);

    }
}

 

직원 스레드는 한 명 손님 쓰레드는 세명!ㅎㅎ

 

결과는???

 

 

CGV 장사 잘 되네

 

쓰레드 넘 신기하고 잼써서

쌤이 걍 대충 넘어가라 하는데두

한번 만들어보았당 ㅋㅋㅋ

잼나~~~

 

 

노트북 사양 구림+인텔리제이 느림

콤보로 저렇게 나왔는데

이클립스로 실행하면 좀 더 이쁘게 나올 수도...??

그래도 만족스~

728x90