Thread 클래스와 Runnable 인터페이스를 사용하여 멀티스레딩을 구현할 수 있다.Thread 클래스를 상속하여 스레드를 생성할 수 있다.class MyThread extends Thread { @Override public void run() { // 스레드가 수행할 작업 for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " - Count: " + i); try { Thread.sleep(1000); // 1초 대기 } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadExample { public static void main(String[] args) { MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); thread1.start(); // 스레드 시작 thread2.start(); // 스레드 시작 } }1) 위의 예제에서 MyThread 클래스는 Thread 클래스를 상속하고 run 메서드를 오버라이드하여 스레드가 수행할 작업을 정의한다.
2)thread1과thread2는 각각 독립적으로 실행된다.
Runnable을 구현한 클래스는 Thread 객체에 전달되어 스레드로 실행된다.class MyRunnable implements Runnable { @Override public void run() { // 스레드가 수행할 작업 for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " - Count: " + i); try { Thread.sleep(1000); // 1초 대기 } catch (InterruptedException e) { e.printStackTrace(); } } } } public class RunnableExample { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread1 = new Thread(myRunnable); Thread thread2 = new Thread(myRunnable); thread1.start(); // 스레드 시작 thread2.start(); // 스레드 시작 } }1) 위의 예제에서
MyRunnable클래스는Runnable인터페이스를 구현하고run메서드를 오버라이드한다.
2)thread1과thread2는MyRunnable객체를 사용하여 각각의 스레드를 실행한다.
Executors를 사용하여 스레드 풀을 생성할 수 있다.import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); // 스레드 풀 생성 for (int i = 0; i < 5; i++) { executor.execute(new MyRunnable()); // 작업 제출 } executor.shutdown(); // 스레드 풀 종료 } }1) 위의 예제에서
Executors.newFixedThreadPool(2)은 두 개의 스레드를 가진 스레드 풀을 생성한다.
2)executor.execute(new MyRunnable())은 스레드 풀에 작업을 제출한다.