프로그램은 실행이 요청되면 메소드 영역 스택 영역 힙 영역 으로 메모리 공간이 할당되고

이 메모리를 기반으로 프로그램이 실행된다.

이렇듯 할당된 메모리 공간을 기반으로 실행 중에 있는 프로그램을 가리켜 '프로세스(process)'라 한다.

프로세스 내에서 프로그램의 흐름을 형성하는 주체를 쓰레드 라고 한다.

하나의 프로세스 내에 둘 이상의 쓰레드가 존재 할 수 있다.


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
public class ShowThread extends Thread{
    String threadName;
    
    public ShowThread(String name){
        threadName=name;
    }
    public void run(){
        for(int i=0; i<100;i++){
            System.out.println(threadName);
            try{
                sleep(100);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
 
class ThreadUnderstand{
    public static void main(String[] args){
        ShowThread st1 = new ShowThread("first");
        ShowThread st2 = new ShowThread("second");
        st1.start();
        st2.start();
    }
}
cs


자바에서는 쓰레드도 인스턴스로 표현을 한다. 때문에 쓰레드의 표현을 위한 클래스가 정의되어야 하며,

이를 위해서는 thread 라는 이름의 클래스를 상속해야 한다.

쓰레드는 쓰레드만의 main 메서드를 지닌다. 단 이름이 main 아닌 run 이다.

sleep()는 Thread 클래스의 static 메소드로서 실행흐름을 일시적으로 멈추는 역할을 한다.

쓰레드의 프로그램의 흐름 형성은 start()메서드를 호출해야 한다.


Runnable 인터페이스

쓰레드 클래스의 정의를 위해서는 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
31
32
33
34
35
36
37
38
public class Sum {
    int num;
    public Sum(){num=0;}
    public void addNum(int n){num+=n;}
    public int getNum() {return num;}
}
 
class AdderThread extends Sum implements Runnable{
    int start, end;
    
    public AdderThread(int s,int e){
        start=s;
        end=e;
    }
    public void run(){
        for(int i =start; i<=end;i++)
            addNum(i);
    }
}
 
public class RuunnableThread {
    public static void main(String[] args){
        AdderThread at1 = new AdderThread(150);
        AdderThread at2 = new AdderThread(51,100);
        Thread tr1 = new Thread(at1);
        Thread tr2 = new Thread(at2);
        tr1.start();
        tr2.start();
        
        try{
            tr1.join();
            tr2.join();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("1~100까지의 합"+(at1.getNum()+at2.getNum()));
    }
}
cs


Runnable 인터페이스는 run 메소드 하나로 이루어져 있다.

Runnable 인터페이스를 구현하는 클래스를 대상으로 start 메소드를 호출할수 없다.

start 메소드는 Thread 클래스의 메소드이기 때문이다.

Thread 클래스에는 Runnable 인터페이스를 구현하는 인스턴스의 참조값을 전달받을 수 있는  생성자가 정의되어 있다.

join() 메소드는 해당 쓰레드가 종료 될 때 까지 실행을 멈출 때 호출하는 메소드이다.

join()메소드가 호출 된 모든 쓰레드가 종료되어야 다음 코드를 실행한다.

'Java' 카테고리의 다른 글

동기화 Synchronization  (0) 2017.02.26
쓰레드의 특성  (0) 2017.02.26
Map<K,V> 인터페이스  (0) 2017.02.26
배열 (Array) / forEach  (0) 2017.02.26
HashSet<E> / TreeSet<E>  (0) 2017.02.26

+ Recent posts