JAVA Thread

sumi Yoo·2023년 1월 25일
0

Thread와 Runnable 차이

Thread 클래스를 상속받으면 다른 클래스를 상속받을 수 없기 때문에 , Runnable 인터페이스를 구현하는 것이 일반적이다.

CustomThread

public class CustomThread extends Thread {

    private String message;
    private int time;

    public CustomThread(String message, int time) {
        this.message = message;
        this.time = time;
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(time);
                System.out.println("Thread 메시지 : " + message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

CustomRunnable

public class CustomRunnable implements Runnable {

    private String message;
    private int time;

    public CustomRunnable(String message, int time) {
        this.message = message;
        this.time = time;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(time);
                System.out.println("Thread 메시지 : " + message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

CustomThreadMain

public class CustomThreadMain {

    public static void main(String[] args) {

        System.out.println("메인함수 실행");

        Thread thread1 = new CustomThread("첫번째 쓰레드", 750);
        Thread thread2 = new CustomThread("두번째 쓰레드", 1500);

        CustomRunnable cr1 = new CustomRunnable("세번째 쓰레드 runnable", 2250);
        CustomRunnable cr2 = new CustomRunnable("네번째 쓰레드 runnable", 3000);

        Thread thread3 = new Thread(cr1);
        Thread thread4 = new Thread(cr2);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

        System.out.println("메인함수 종료");
    }
}

0개의 댓글