늦은 프로그래밍 이야기

Thread 본문

내일배움캠프/Java 심화

Thread

한정규 2022. 12. 2. 19:54

Thread

 - 프로세스(Process) : 동작하고 있는 프로그램.

 - 쓰레드를 이용하면 한 프로세스에서 두가지 이상의 일을 동시에 할 수 있다

 

 - 동시성 : 프로세스 하나가 여러 진행중인 작업을 바꾸면서 수행 (context switching)

 - 병렬성 : 프로세스 하나에 여러 코어들이 각각 동시에 여러 작업들을 수행

 

Thread 클래스

생성

 - java.lang.Thread 클래스를 상속 받는다.

 - run() 메소드를 오버라이딩 한다.

 - Thread 클래스의 sleep(millisecond) 메소드로 실행을 일시정지 할 수 있다.

public class MyThread1 extends Thread {   // java.lang.Thread 클래스를 상속 받는다.
    String str;
    public MyThread1 (String str) {
        this.str = str;
    }

    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(str);

            try {
                Thread.sleep((int) (Math.random()*1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

실행

 - run() 메소드가 아닌 strat() 메소드로 쓰레드를 실행 시킨다.

 - 메인 쓰레드가 종료되어도 다른 쓰레드들이 작업을 수행 중이면 프로그램은 종료되지 않는다.

public static void main(String[] args) {
    MyThread1 t1 = new MyThread1("*");
    MyThread1 t2 = new MyThread1("-");

    t1.start();     // 쓰레드를 실행
    t2.start();

    System.out.println("main end");  // 메인쓰레드 종료 알림
}

Runnable 인터페이스

 - 쓰레드를 생성하고 싶은 클래스가 이미 다른 클래스를 상속 받는다면 Thread 클래스를 상속 받을 수 없게 된다.

 - Thread 클래스를 상속 받을 수 없을 때 Runnable 인터페이스를 구현한다.

생성

 - Runnable 인터페이스를 구현한다.

 - run() 메소드를 오버라이딩 한다.

 - 마찬가지로 Thread 클래스의 sleep(millisecond) 메소드로 실행을 일시정지 할 수 있다.

public class MyThread2 implements Runnable {
    String str;
    public MyThread2 (String str) {
        this.str = str;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(str);

            try {
                Thread.sleep((int)(Math.random()*100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

실행

 - Runnable 인터페이스에는 run() 메소드만 존재하고 strat() 메소드가 없기 때문에 따로 Thread 클래스로 생성해야 한다.

 - strat() 메소드로 쓰레드를 실행 시킨다.

 - 모든 쓰레드가 종료될 때까지 프로그램은 종료되지 않는다.

public static void main(String[] args) {
    MyThread2 t1 = new MyThread2("*");
    MyThread2 t2 = new MyThread2("-");

    Thread thread1 = new Thread(t1);
    Thread thread2 = new Thread(t2);

    thread1.start();
    thread2.start();

    System.out.println("main end");
}

우선순위

 - getPriority() 메소드와 setPriority() 메소드를 사용하여 쓰레드의 우선순위를 반환하거나 변경할 수 있다.

 - 우선순위의 범위는 1부터 10까지 이고, 숫자가 높을수록 우선순위가 높아진다. (기본 : 5)

 - 우선순위가 10인 스레드는 우선순위가 1인 스레드보다 좀 더 많이 실행 큐(Queue)에 포함되어 좀 더 많은 작업 시간을 할당받는다.

thread2.setPriority(10); // Thread2 의 우선순위를 10으로 변경

thread1.start();
thread2.start();

System.out.println(thread1.getPriority()); // 5
System.out.println(thread2.getPriority()); // 10

'내일배움캠프 > Java 심화' 카테고리의 다른 글

추상클래스 vs 인터페이스  (0) 2022.12.01
Mutable, Immutable  (0) 2022.12.01
Wrapper 클래스  (0) 2022.11.30
필드, 메소드의 구분 / Block / Scope  (0) 2022.11.30
JVM 구조  (0) 2022.11.30
Comments