의문점 공부하기/📌 Java

📌 스레드 만드는 방법!!!!

아리빠 2023. 7. 19. 16:37

Thread 클래스를 상속받기

  • Thread 클래스를 상속받아 새로운 클래스를 정의하고, run() 메소드를 오버라이딩하여 스레드가 실행할 작업을 정의한다. 그리고 해당 클래스의 객체를 생성하고 start() 메소드를 호출하여 스레드를 시작한다
class MyThread extends Thread {
    public void run() {
        // 스레드가 실행할 작업 정의
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

Runnable 인터페이스를 구현하기

  • Runnable 인터페이스를 구현하는 클래스를 정의하고, run() 메소드를 구현하여 스레드가 실행할 작업을 정의한다. 그리고 해당 클래스의 객체를 생성하고 Thread 클래스의 생성자에 해당 객체를 전달하여 스레드를 생성한다. start() 메소드를 호출하여 스레드를 시작!
class MyRunnable implements Runnable {
    public void run() {
        // 스레드가 실행할 작업 정의
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

람다식을 사용하기

  • Runnable 인터페이스를 구현하는 클래스를 정의하지 않고, 람다식을 사용하여 스레드가 실행할 작업을 정의할 수도 있다
  •  
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // 스레드가 실행할 작업 정의
        });
        thread.start();
    }
}