1. Thread


프로세스의 자원을 이용해서 실제로 수행하는 것이 Thread 이다.
- 개별적인 메모리공간(호출스택)을 필요로 한다.
- main Thread : main method의 작업을 수행하는것도 Thread이다.
- 실행중인 사용자 Thread 가 하나도 없을 때 프로그램은 종료한다.
  (=> main Thread가 끝나도 끝나지 않은 Thread가 있다면 프로그램은 종료되지 않음)

2. run() & start()


▶run()  
- Thread를 통해 작업하고자 하는 내용으로 run()의 { } 안을 채운다.
- main method에서 run을 호출하는 것은 생성된 Thread를 실행시키는 것이 아니라 
  단순히 class에 선언된 method를 호출하는 것.
▶start()
- 새로운 Thread가 작업을 실행하는데 필요한 호출스택(call stack)을 생성한 다음 run() 호출 
  →생성된 호출스택에 run()이 첫번째로 올라가게 한다.

3. Thread의 life Cycle

 

-쓰레드가 생성되면 아래 그림이 보여주는 네가지 상태 중 한가지 상태에 있게 된다.

 

 

3-1.
new 상태 : Thread class가 키워드 new를 통해서 인스턴스화 된 상태
runnable 상태 : start method 호출 후. 모든 실행의 준비를 마치고 스케쥴러에 의해 실행의 대상으로 선택되기를 기다리는 상태
blocked 상태 : 실행중인 Thread가 sleep 이나 join 메소드를 호출하는 등의 상황에서 cpu를 다른 thread에게 양보하고,
                        그 thread는 blocked상태가 된다.
dead 상태 : run 메소드의 실행이 완료되어서 run 메소드를 빠져나오게 되면 해당 thread는 dead 상태가 된다.
                   thread의 실행을 위해 할당받았던 메모리 등 모든 정보가 소멸.


4. Thread를 구현하는 방법

4-1. Thread class를 상속받는 방법


-Thread를 상속받은 클래스의 인스턴스를 생성한다.

 

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
 
//Single Thread
public class SingleThreadEx extends Thread{
   public int[] temp;
   public SingleThreadEx(String threadname){        //생성자 함수 (main에서 SingleThreadEx의 "첫번째"를 받음)
      super(threadname);    //참조변수
      temp = new int[10];    //배열 생성
      for(int start = 0; start < temp.length; start++){        
         temp[start] = start;    //배열 temp[start]에 값이 들어감.
      }
   }
   
   public void run(){    //Thread class의 run()을 오버라이딩
      for(int start : temp){
         try
            sleep(1000);        //1초 지연
         }catch (InterruptedException ie){    // 예외처리
            ie.printStackTrace();    //오류가 뭔지 찍어주는 함수
         }
         System.out.printf("스레드 이름 : %s ,",currentThread().getName());    //현재 thread의 이름(첫번째) 출력
         System.out.printf("temp value : %d %n", start);        //start의 값 찍어줌.
      }
   }
   public static void main(String[] args){
      SingleThreadEx st = new SingleThreadEx("첫번째");    //생성자가 불러진다.
      st.start();    // runnable 대기상태로 가서 스케쥴러가 run을 
   }
   
   
}
cs

 

4-2. Runnable interface를 구현하는 방법


-Runnable을 구현한 class의 인스턴스를 생성
-Runnable interface를 구현한 class의 instance를 생성한 다음, 이 instance를 Thread class의 생성자의 매개변수로 제공

 

 

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
public class Thread1 implements Runnable{
   private int[] temp;
   public Thread1(){
       temp=new int[10];
      for(int start=0; start<temp.length; start++){
         Thread.currentThread().setName("첫번째");
         temp[start]=start;
      }
   }
   public void run(){
      for(int start:temp){
         try{
            Thread.sleep(1000);
         }
         catch(InterruptedException ie){
            ie.printStackTrace();
            
         }
         System.out.printf("스레드 이름:%s", Thread.currentThread().getName());
         System.out.printf("temp value:%d %n",start);
      }
   }
    public static void main(String[]ar){
       Thread1 st= new Thread1();
       Thread ct = new Thread(st,"첫번째");
       ct.start();
    }
}
cs

 

 

(코드 둘 다 출력값은 똑같다)

'Java > Java' 카테고리의 다른 글

[Java] Thread_2  (0) 2017.09.04

+ Recent posts