자바(JAVA)

자바(JAVA) - Thread사용하기(implements)

yes or yes 2017. 8. 14. 13:56
반응형

package Day3;
//extends를 사용하지 않고 implements를 사용한 Thread
public class SingleThreadEx1 implements Runnable{   
 public int[] temp;     //temp안에 int배열 선언
 public SingleThreadEx1(){   //생성자
  temp = new int[10];    //temp안의 int형 배열을 10으로 선언
  for(int start = 0; start < temp.length; start++){ // 0부터 9까지 for문
   temp[start] = start; //초기화  for문 돌린걸 temp안의 배열에 넣는다
  }
 }
 
 public void run(){
  for(int start : temp){    //start에서 temp까지 for문
   try{        
    Thread.sleep(1000);    //예외처리 (1초마다 출력)
   }catch (InterruptedException ie){
    ie.printStackTrace();
   }
   System.out.printf("스레드 이름 : %s ,",Thread.currentThread().getName()); //현재 쓰레드의 이름을 반환해준다 (메인에 있는 "첫번쨰")
   System.out.printf("temp value : %d %n", start); //temp value : 쓰레드의 for문 배열 돌린 값을 넣는다
   
  }
 }
 public static void main(String[] args){
  SingleThreadEx1 st = new SingleThreadEx1();   //객체선언 및 생성
  Thread th = new Thread(st, "첫번쨰");     //객체선언 및 생성(환경, 쓰레드의 이름 )
  th.start();           //쓰레드 시작
 }
}

 
 
 

 

반응형