티스토리 뷰

자바에서ThreadRunnable은 멀티스레딩을 지원하기 위한 클래스와 인터페이스입니다. 멀티스레딩은 여러 스레드를 동시에 실행하여 프로그램의 성능을 향상시키거나 동시에 여러 작업을 수행할 수 있는 기능입니다.

 

Thread 클래스

java.lang.Thread 클래스는 자바에서 스레드를 생성하고 관리하는 기본 클래스입니다. 새로운 스레드를 생성하려면 Thread 클래스를 상속받고, run() 메서드를 오버라이드하여 스레드에서 실행할 작업을 정의합니다. 그 후, 스레드 객체를 생성하고 start() 메서드를 호출하여 스레드를 실행합니다.

 

예시

class MyThread extends Thread {
    @Override
    public void run() {
        // 스레드에서 실행할 작업
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 스레드 실행
    }
}

 

Runnable 인터페이스

java.lang.Runnable 인터페이스는 스레드에서 실행할 작업을 정의하기 위한 인터페이스입니다. Thread 클래스를 상속받지 않고, Runnable 인터페이스를 구현하여 스레드에서 실행할 작업을 정의할 수 있습니다. 이렇게 하면 다른 클래스를 상속받을 수 있는 유연성을 제공합니다. Runnable 인터페이스를 구현한 클래스의 인스턴스를 Thread 생성자에 전달하여 스레드를 생성하고 실행할 수 있습니다.

 

예시

class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 스레드에서 실행할 작업
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start(); // 스레드 실행
    }
}

Thread와 Runnable의 선택은 상황에 따라 달라집니다. 다른 클래스를 상속받아야 하는 경우Runnable 인터페이스를 구현하는 것이 좋습니다. 그러나 스레드 자체에 대한 동작을 변경하거나 추가해야 하는 경우, Thread 클래스를 상속받는 것이 더 적합합니다. 일반적으로, Runnable 인터페이스를 사용하는 것이 더 유연한 설계를 가능하게 합니다.

 

Runnarble 과 Thread를 같이 사용한 예시
// Runnable 인터페이스를 구현한 클래스
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
			System.out.println("main :" + i);
			try {
				Thread.sleep(1500);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
    }
}

// Thread 클래스를 상속한 클래스
class MyThread extends Thread {
    @Override
    public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println("main :" + i);
			try {
				Thread.sleep(1500);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
    }
}

public class Main {
    public static void main(String[] args) {
        // Runnable 인터페이스를 사용하는 경우
        Runnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable);
        thread1.start();

        // Thread 클래스를 사용하는 경우
        MyThread thread2 = new MyThread();
        thread2.start();
        
        // 		결과
        //		Thread 1 : 0
		//		Thread 2 : 0
		//		Thread 2 : 1
		//		Thread 1 : 1
		//		Thread 2 : 2
		//		Thread 1 : 2
		//		Thread 2 : 3
		//		Thread 1 : 3
		//		Thread 2 : 4
		//		Thread 1 : 4
        // Thread1과 Thread2가 동시에 실행되는 모습을 확인할 수 있다.
        // thread1.run() 과 thread2.run() 으로 함수를 실행한다면 출력결과는
        // 보통과 같이 thread1출력이끝나고 thread2가 실행될것이다.
        
        // 그래서 runnable을 thread화시켜 start()함수를 사용해야
        // 다중 쓰래드형식(동시실행)이 가능하다
     
        
    }
}

'JAVA > java 기초' 카테고리의 다른 글

JAVA예외처리(Exception)  (0) 2023.04.14
JAVA 싱글톤이란?(Singleton)  (0) 2023.04.14
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함