Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter04 : ObjectShare 본문

JAVA/chapter21_thread

chapter04 : ObjectShare

GAWON 2023. 5. 30. 18:32
package org.joonzis.ex;
class MusicBox{
	public void rock() {
		for(int i=0; i<5; i++) {
			System.out.println("play the rock");

			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public void ballad() {
		for(int i=0; i<5; i++) {
			System.out.println("play the ballad");

			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public void dance() {
		for(int i=0; i<5; i++) {
			System.out.println("play the dance");

			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
class MusicPlayer extends Thread{
	private int type;
	private MusicBox musicBox;
	public MusicPlayer(int type, MusicBox musicBox) {
		this.type = type;
		this.musicBox = musicBox;
	}
	
	@Override
	public void run() {
		switch (type) {
		case 1:musicBox.rock();
			break;
		case 2:musicBox.ballad();
			break;
		case 3:musicBox.dance();
			break;
		}
	}
}
public class Ex04_ObjectShare {
	public static void main(String[] args) {
		MusicBox box = new MusicBox();
		
		MusicPlayer p1 = new MusicPlayer(1, box);
		MusicPlayer p2 = new MusicPlayer(2, box);
		MusicPlayer p3 = new MusicPlayer(3, box);
		
		p1.start();
		p2.start();
		p3.start();
		
		
	}
}

'JAVA > chapter21_thread' 카테고리의 다른 글

chapter06 : synchronized  (0) 2023.05.30
chapter05 : synchronized  (0) 2023.05.30
chapter03 : mulitThread  (0) 2023.05.30
chapter02 : multiThread  (0) 2023.05.30
chapter01 : mainThread  (0) 2023.05.30