Java Thread (1)

정미·2022년 7월 24일
0

Computer Science

목록 보기
40/81
post-thumbnail

Process vs Thread

Process vs Thread

Java Thread

JVM에 의해 스케줄되는 실행 단위 코드 블록

  • JVM이 OS의 역할
  • 일반 스레드와 거의 차이가 없다.
  • 자바에는 프로세스가 존재하지 않고 스레드만 존재한다.
  • main 메서드 작업을 main 스레드에서 수행한다.

구현

스레드를 통해 작업하고 싶은 내용을 run() 메서드에 작성

1. Thread 클래스 상속

  • 다른 클래스를 상속받을 수 없다.
class ThreadExtendsClass extends Thread {
	@Override
	public void run() {
		System.out.println(getName());  // 현재 실행중인 스레드 이름

		try {
			Thread.sleep(10);  // 스레드를 0.01초 멈춤
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class Thread implements Runnable {
	..
	public final String getName() {
		return name;
	}
	..
}

2. Runnable 인터페이스 구현

  • 더 일반적인 방법
class ThreadImplementsInterface implements Runnable {
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());

		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public interface Runnable {
	public abstract void run();
}

실행

  • 스레드는 독립적인 작업을 수행하기 위해 자신만의 호출스택이 필요하다.
    • 새로운 스레드를 생성, 실행할 때마다 새로운 호출스택 생성. 스레드 종료되면 호출스택 소멸

start()

public class Application {
	public static void main(String[] args) {
		ThreadExtendsClass thread1 = new ThreadExtendsClass();
		Thread thread2 = new Thread(new ThreadImplementsInterface());

		thread1.start();
		thread2.start();
		// thread2.run();
	}
}
public synchronized void start() {
      
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
 
        group.add(this);
 
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            
            }
        }
}

private native void start0();
 
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
}

start() 실행 과정

  1. main 메서드(스레드)에서 스레드의 start() 호출
  2. start()는 새로운 스레드와 사용할 호출스택 생성
  3. 새로 생성된 호출스택에 run() 호출. 스레드가 독립된 공간에서 작업 수행
  4. 스케줄러가 정한 순서에 의해 2개의 호출 스택이 번갈아가며 실행

run() 실행 과정

  1. main 메서드에서 오버라이딩한 run()을 직접 호출
  2. 새로운 스레드가 생성되지 않고 main 스레드 호출스택에 run()을 호출한다.

출처

0개의 댓글