스레드(thread) : 자바 프로그램의 명령 실행 흐름

멀티스레드 프로그램의 작성 방법
Thread 클래스를 이용하거나 Runnable 인터페이스를 이용하여 작성.

 1. Thread 클래스
run() 메소드를 구현해서 start();해주면 동작을 시작
sleep();   //  1/1000초 단위로 thread 실행을 잠시 정지


예제) A~Z까지 출력하는 스레드와 0~9까지 출력하는 스레드를 동시에 출력

1) main 메소드를 포함하는 클래스 (A~Z 출력)
package 멀티스레드;
class MultithreadExample1 {
    public static void main(String args[]) {
        Thread thread = new DigitThread();  // 스레드를 생성
        thread.start(); // 스레드를 시작
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            System.out.print(ch);
            try {
                Thread.sleep(1000);  // 주어진 시간이 경과되길 기다리는 메소드
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
------------------------------------------------
2) 숫자를 출력하는 스레드 클래스 (0~9 출력)
package 멀티스레드;
class DigitThread extends Thread {
    public void run() {
        for (int cnt = 0; cnt < 10; cnt++) {
            System.out.print(cnt);
            try {
                Thread.sleep(1000);  // 주어진 시간이 경과되길 기다리는 메소드
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
------------------------------------------------
3) 결과


 Thread.sleep(1000)을 써서 1초간 스레드 실행 정지하며 천천히 출력되어 늘려진 시간 간격으로 인해 문자와 숫자가 좀 더 골고루 출력된다.




2. Runnable 인터페이스
main 메소드를 포함하는 클래스와 이 스레드가 할 일을 기술하여 main에 implements

Runnable 인터페이스를 구현하는 클래스로 스레드를 만들기 위해서는 이 클래스의 객체를 생성한 다음에 그 객체를 생성자 파라미터로 삼아서 Thread 객체를 생성해야 한다.




스레드 간의 데이터 교환


크리티컬 섹션(critical section)의 동기화

한번에 하나 이상의 스레드가 들어올 수 없게

동기화 블럭
synchronized(객체) {
}



동기화 메소드
synchronized 리턴타입 메소드명() {
}


예제)
public class CalcThread extends Thread { // 파이를 계산 
    SharedArea sharedArea;
    CalcThread(SharedArea sharedArea) {
    this.sharedArea = sharedArea;
    }
public void run() {
    double total = 0.0;
    for (int cnt = 1; cnt < 1000000000; cnt += 2)
    if (cnt / 2 % 2 == 0)
    total += 1.0 / cnt;
    else
    total -= 1.0 / cnt;
    synchronized (sharedArea) {
    sharedArea.result = total * 4;
    sharedArea.isReady = true;
    } 
}
}
----------------------------------------------------------
public class PrintThread extends Thread { // 파이를 출력
    SharedArea sharedArea;
    PrintThread(SharedArea sharedArea) {
    this.sharedArea = sharedArea;
    }
public void run() {
    while(sharedArea.isReady != true) {
    try{
        Thread.sleep(100);
        }catch(Exception e){}
        }
    synchronized (sharedArea) {
    System.out.println(sharedArea.result);
    }
}
}
-----------------------------------------------------------

public class SharedArea {
    double result;
    boolean isReady;
}
---------------------------------------------------------

public class ThreadExample3 {
    public static void main(String[] args) {
    SharedArea obj = new SharedArea();
    CalcThread thread1 = new CalcThread(obj);
    PrintThread thread2 = new PrintThread(obj);
    thread1.start();
    thread2.start();
    }
}


스레드간의 신호 전송
신호를 보내는 notify 메소드와 신호를 받는 wait 메소드

객체.notify();
객체.wait();
객체.notifyAll();




스레드 상태를 알아내는 메소드

getState();

NEW : 실행되기 전
RUNNABLE : 실행 가능 상태
WAITING :  wait 메소드를 호출하고 있는 상태
TIMED_WAITING : sleep 메소드를 호출하고 있는 상태
BLOCKED : 다른 스레드의 동기화 블록이나 동기화 메소드가 끝나기를 기다리고 있는 상태
TERMINATED 실행을 마친 상태





public class CalcThread  extends Thread{ // 파이를 계산 

SharedArea sharedArea;

CalcThread(SharedArea sharedArea){

this.sharedArea = sharedArea;

}

public void run(){

double total = 0.0;

for (int cnt = 1; cnt < 1000000000; cnt += 2)

           if (cnt / 2 % 2 == 0)

               total += 1.0 / cnt;

           else

               total -= 1.0 / cnt;

 synchronized (sharedArea) {

sharedArea.result = total * 4;

sharedArea.isReady = true;

}  

}

}

----------------------------------------------------------

public class PrintThread extends Thread{ // 파이를 출력

SharedArea sharedArea;

PrintThread(SharedArea sharedArea){

this.sharedArea = sharedArea;

}

public void run(){

while(sharedArea.isReady != true){

try{

Thread.sleep(100);

}catch(Exception e){}

}

synchronized (sharedArea){

System.out.println(sharedArea.result);

}

}


}

-----------------------------------------------------------

public class SharedArea {

double result;

boolean isReady;

}

---------------------------------------------------------


public class ThreadExample3 {

public static void main(String[] args) {

SharedArea obj = new SharedArea();

CalcThread thread1 = new CalcThread(obj);

PrintThread thread2 = new PrintThread(obj);

thread1.start();

thread2.start();

}

}









Posted by netyhobby
,