Thread 예제2 sleep로 지연시키

·2022년 11월 3일
0

JAVA객체지향_Thread

목록 보기
3/7

네이버 메인에서 기사 헤드라인을 한줄씩 보여주는 원리

1. 큰 틀 작성: 스레드, main메소드

class NewsThread extends Thread{
	public void run(){
   	}
}
public class Test{
	public static void main(String[]args){
    	new NewsThread().start();
    }
}

2.구현부 작성

class NewsThread extends Thread{
//뉴스 헤드라인들을 가진 String 배열 생성
// "앞에 \을 써주면 String 처리됨
	String[] news = {
    	"[이태원 참사] '그날 밤' 서울청 112상황실에선 무슨 일이",
        "일본 수도권서 규모 5.0 지진…도쿄서도 진도3 흔들림",
        "오늘부터 초겨울 추위…서울 아침 최저기온 '0도'",
        "[속보] 한미 \“맞춤형 억제전략 개정 내년까지 완료 추진\”", 
        "다음 이메일, 한때 접속 오류 발생…\“20분만에 복구 완료\”"
    }
	public void run(){
    	int n = 0;
    	while(true){
        //헤드라인 배열을 한줄씩 출력
        	System.out.println(news[n]);
            //배열길이만큼 돌면 n을 0으로 초기화.
            if(n==news.length) n=0;
            n++;
            //sleep() => InterruptedException 예외발생
            try{
           		Thread.sleep(1000);		//1초동안 스레드 지연
            }catch(InterruptedException ie){
                	System.out.println(ie.getMessage());
            }
        }
   	}
}
public class Test{
	public static void main(String[]args){
    	new NewsThread().start();
    }
}
profile
웹개발입문자

0개의 댓글