공유객체 : 하나의 객체를 여러개의 쓰레드가 사용
메소드 동시호출 막기
public synchronized void playMusicA(){
for(int i = 0; i < 10; i ++){
System.out.println("신나는 음악!!!");
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}// for}//playMusicA
효과
종료
활용
public void playMusicB(){
for(int i = 0; i < 10; i ++){
synchronized(this){
System.out.println("슬픈 음악!!!");
}
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}// for}//playMusicB
synchronized(this){ . . . };