본문 바로가기
CLASS/JAVA

#19 / Thread (class 형태 , interface 형태)

by eungSe__ 2024. 5. 31.
⚡ Thread (class 형태 , interface 형태)
public class thread1 {
//Thread (class 형태 , interface 형태)
	public static void main(String[] args) {
		//-- class 형태 Thread 호출
//		int w = 0;
//		while( w < 100 ) {
//			th_box1 th = new th_box1(w);
//			th.start(); //뒤죽박죽 출력
//			
//			w++;
//		}
		
		//-- interface 형태 Thread 호출
		int w = 0;
		while( w < 100 ) {
			Runnable ra = new th_box2(w);
			//ra.run(); //1개의 thread : 순서대로 작업 출력
			
			Thread tr = new Thread(ra);

			tr.start(); //뒤죽박죽 출력
			
			w++;
		}
	}

}

class th_box1 extends Thread{ //class형태 Thread
	int no = 0;
	public th_box1(int z) {
		this.no = z;
	}
	
	@Override
	public void run() { //오버로딩을 하지 못함 : 커스텀 불가
		try {
			Thread.sleep(5000); //5초후 실행
			System.out.println(this.no);
		}catch(Exception e) {
			System.out.println("cpu 스레드 중 문제의 스레드가 발생되었습니다");
		}
	}
}

class th_box2 implements Runnable{ //interface형태 Thread
	int no = 0;
	public th_box2(int z) {
		this.no = z;
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(5000); //5초후 실행
			System.out.println(this.no);
		}catch(Exception e) {
			System.out.println("cpu 스레드 중 문제의 스레드가 발생되었습니다");
		}
	}
}

 

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

#20-2 / generic code 형태의 class  (1) 2024.06.11
#20-1 / 람다(lamda)코드 사용 방식  (1) 2024.06.11
#18-2 / Thread를 이용한 멀티 서버  (0) 2024.05.27
#18-1 / 서버 - UDP  (0) 2024.05.27
#17 / remind3  (0) 2024.05.24