쓰레드와 공유객체

말하는 감자·2025년 1월 3일
0

자바 중급

목록 보기
20/21
post-thumbnail

개념

하나의 객체를 여러개의 Thread가 사용

Code 예시

public class MusicBox {
    public void playMusicA(){
        System.out.println("신나는 음악");
        try {
            Thread.sleep((int)(Math.random()*1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void playMusicB(){
        System.out.println("웅장한 음악");
        try {
            Thread.sleep((int)(Math.random()*1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }public void playMusicC(){
        System.out.println("조용한 음악");
        try {
            Thread.sleep((int)(Math.random()*1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class MusicPlayer extends Thread{
    int type;
    MusicBox musicBox;

    // 생성자로부터 musicbox와 정수type을 받아들여서 필드 초기화
    public MusicPlayer(int type,MusicBox musicBox){
        this.type=type;
        this.musicBox=musicBox;
    }

    public void run(){
        switch (type){
            case 1:
                musicBox.playMusicA();
                break;
            case 2:
                musicBox.playMusicB();
                break;
            case 3:
                musicBox.playMusicC();
                break;
        }
    }
}
public class MusicBoxExam {
    public static void main(String[] args) {
        MusicBox musicBox=new MusicBox();

        MusicPlayer kim=new MusicPlayer(1,musicBox);
        MusicPlayer lee=new MusicPlayer(2,musicBox);
        MusicPlayer park=new MusicPlayer(3,musicBox);

        kim.run();
        lee.run();
        park.run();
    }
}

결과

profile
주니어개발자(?)

0개의 댓글