🎨 Programming/JAVA

[JAVA] 30. 스레드(thread) - 1

ryang x2 2021. 3. 22. 13:17
728x90
반응형

# 프로세스(process) 

실행중인 프로그램을 뜻합니다. 프로그램을 실행하면 OS로부터 실행에 필요한 자원(메모리)을 할당받아 프로세스가 만들어집니다. 

 

# 스레드(Thread) 

프로세스(process)의 자원을 이용해서 실제로 작업을 수행하는 것이 스레드입니다.
프로그램을 실행하는 하나의 단위를 말한다. 모든 프로세스에는 한 개 이상의 스레드가 존재하여 작업을 수행합니다.(멀티 스레드) 


예를 들어) 게임을 만들때 배경음악을 사용하고 싶다면 멀티스레드를 만들어야한다. 단일 스레드일경우, 음악이 끝나면 게임이 시작하게 된다.

 

# 멀티 스레딩 

하나의 프로세스 내에서 여러 스레드가 동시에 작업을 수행하는 것을 말합니다. 실제로는 한 개의 CPU가 한 번에 작업만 수행할 수 있기 때문에 아주 짧은 시간 동안 여러 작업을 번갈아 가며 수행함으로써 동시에 여러 작업이 수행되는 것처럼 보이게 하는 것입니다.

 

 

● 스레드 실행하는 방법 

1. Thread 클래스를 상속 (다중 상속이 어렵기 때문에 신중히 사용한다.!)

* 강제성있는 메소드는 없지만 무조건 할일을 구현하는 메소드 run()를 생성한다.

* Thread가 만들어지면 run 메소드 호출하여 자동으로 구현

 

1) 상속 예시

public class PrintThread1 extends Thread{
    @Override
    public void run() {
        for (int i=0; i<10; i++){
            if (i%2 == 0){ // 짝수라면
                System.out.println("PrintThread1 : " + i); // i값 노출
            }
            try{
                Thread.sleep(500); // sleep(); : 잠깐 잠깐 멈추는 클래스 // 500 = 0.5초
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    // 하나의 작업단위 완성
}

2) main

public class Thread1 {
    public static void main(String[] args) {
        Thread th1 = new PrintThread1();  // 1. Thread 클래스 상속
        
        th1.start(); // main Thread가 시작해라


        for (int i=0; i<10; i++){
            if (i%2 == 0){ // 짝수라면
                System.out.println("main : " + i);
            }
            try{
                Thread.sleep(500);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

 

2. Runnable 인터페이스를 구현

* 강제로 할일을 구현하는 메소드 run()를 생성한다. 안할시 에러발생

* Thread 클래스 생성자에 Runnable 인터페이스를 구현한 객체를 매개변수로 넣습니다.

 

1) 인터페이스 구현

public class PrintThread2 implements Runnable {
    @Override
    public void run() {
        for (int i=0; i<10; i++){
            if (i%2 == 0){
                System.out.println("PrintThread2 : " + i);
            }
            try{
                Thread.sleep(500);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

2) main

public class Thread1 {
    public static void main(String[] args) {
        Thread th1 = new PrintThread1();  // 1) Thread 클래스 상속 
        Runnable r1 = new PrintThread2(); // 2) Runnable 인터페이스를 구현
        Thread th2 = new Thread(r1); 
        // Thread 클래스 생성자에 Runnable 인터페이스를 구현한 객체를 매개변수로 넣습니다.

        th1.start(); 
        th2.start();


        for (int i=0; i<10; i++){
            if (i%2 == 0){ // 짝수라면
                System.out.println("main : " + i);
            }
            try{
                Thread.sleep(500);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

 

 

3. 익명클래스를 사용하는 방법

public class Thread1 {
    public static void main(String[] args) {

	Thread th3 = new Thread(new Runnable() { // 3) 익명 클래스 사용
            @Override
            public void run() {
                for (int i=0; i<10; i++){
                    if (i%2 == 0){
                        System.out.println("익명객체 : " + i);
                    }
                    try{
                        Thread.sleep(500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

 

3-1. 익명 객체를 람다식으로 표현하는 방법

* 람다 표현식 : 메소드를 하나의 식으로 표현한 문법

기존 메소드방법)
int min(int x, int y){ // int x = 7 , int y = 10;
return x < y ? x : y;
}

int result = min(7, 10);

람다 표현식)
(매개변수 목록) -> { 메소드 실행문 }
(x,y) -> x > y ? x : y;

 

Thread th3 = new Thread(() -> { // () 안에는 Runnable 이 생략되어있는 부분이다.
            for (int i=0; i<10; i++){
                    if (i%2 == 0){
                       System.out.println("익명객체 : " + i);
                   }
                    try{
                        Thread.sleep(500);
                   }catch (InterruptedException e){
                        e.printStackTrace();
                    }
               }
        });

 

728x90
반응형