FreeHand

병렬처리(Thread, Stream) 본문

Language/Java

병렬처리(Thread, Stream)

Jinn 2024. 2. 19. 01:38
public class Main {
    public static void main(String[] args) {
        // Thread 생성
        MyThread1 t1 = new MyThread1();
        Thread t2 = new Thread(new MyThread2());
        
        // Thread 실행
        t1.start();
        t2.start();
    }
}

// Thread 클래스 상속
class MyThread1 extends Thread {
    public void run() {
        for (int i=0; i<100; i++) {
            System.out.println(this.getName()); // Thread-0
        }
    }
}

// Runnable 인터페이스 구현
class MyThread2 implements Runnable {
    public void run() {
        for (int i=0; i<100; i++) {
            System.out.print(Thread.currentThread().getName() + " "); // Thread-1
        }
    }
}

 

실행 결과

 

Thread의 실행 순서는 OS의 스케줄러가 결정함. OS에 의존적임.

start()는 새로운 call stack을 생성하고 거기서 run()을 호출함. 쓰레드마다 개별 호출 스택을 갖게됨.

 

쓰레드는 사용자 쓰레드와 데몬 쓰레드로 나뉨. 실행중인 사용자 쓰레드가 없을 때 프로그램이 종료됨.

 

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

자바로 구현한 디자인 패턴  (0) 2024.05.12
스트림1  (0) 2024.01.07
함수형 인터페이스  (0) 2024.01.07
익명 클래스  (0) 2024.01.06
내부 클래스  (0) 2024.01.06