[Java] Thread

·2022년 10월 16일

JAVA

목록 보기
9/10

Thread


한 프로세스 내에서 여러 쓰레드를 이용하면 여러 가지 일을 동시에 수행할 수 있다.

public class Exmple extends Thread {
    public void run() {
        System.out.println("thread run.");
    }

    public static void main(String[] args) {
        Example example = new Example();
        example.start();  // start()로 쓰레드를 실행한다.
    }
}

Thread 클래스를 상속받고, thread 클래스의 run 메소드를 구현하면 해당 thread를 start할 때 run 메소드가 수행된다.

import java.util.ArrayList;

public class Sample extends Thread {
    int seq;
    public Sample(int seq) {
        this.seq = seq;
    }

    public void run() {
        System.out.println(this.seq+" thread start.");
        try {
            Thread.sleep(1000);
        }catch(Exception e) {
        }
        System.out.println(this.seq+" thread end.");
    }

    public static void main(String[] args) {
        ArrayList<Thread> threads = new ArrayList<>();
        for(int i=0; i<10; i++) {
            Thread t = new Sample(i);
            t.start();
            threads.add(t);
        }

        for(int i=0; i<threads.size(); i++) {
            Thread t = threads.get(i);
            try {
                t.join(); // t 쓰레드가 종료할 때까지 기다린다.
            }catch(Exception e) {
            }
        }
        System.out.println("main end.");
    }
}

thread는 동시에 실행하면 순서와 상관없이 실행되고, 별도의 처리 없이는 스레드를 실행한 main 메소드가 먼저 종료되어버릴 수 있다. 따라서 위와 같이 join 메서드를 활용해 모든 스레드 종료 후 main 메소드를 종료시키도록 할 수 있다. join 메서드는 스레드가 종료될 때까지 기다리게 하는 메서드이다.

Runnable


스레드를 만들 때 위처럼 Thread를 상속받아 만들기도 하지만, 주로 Runnable 인터페이스를 구현하는 방법을 주로 사용한다. Thread 상속 시 다중 상속이 불가능하므로 다른 클래스를 상속받으면서 쓰레드를 구현하기 위해서이다.
위에서 작성한 예제를 아래와 같이 바꿀 수 있다.

import java.util.ArrayList;

public class Sample implements Runnable {
    int seq;
    public Sample(int seq) {
        this.seq = seq;
    }

    public void run() {
        System.out.println(this.seq+" thread start.");
        try {
            Thread.sleep(1000);
        }catch(Exception e) {
        }
        System.out.println(this.seq+" thread end.");
    }

    public static void main(String[] args) {
        ArrayList<Thread> threads = new ArrayList<>();
        for(int i=0; i<10; i++) {
            Thread t = new Thread(new Sample(i));
            t.start();
            threads.add(t);
        }

        for(int i=0; i<threads.size(); i++) {
            Thread t = threads.get(i);
            try {
                t.join();
            }catch(Exception e) {
            }
        }
        System.out.println("main end.");
    }
}

 

 


이 글은 점프 투 자바를 읽고 스터디한 글입니다.

0개의 댓글