하나의 객체를 여러개의 Thread가 사용
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();
}
}
