-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
스레드와 Runnable 스레드 생성
- 스레드는 Thread 클래스를 상속하거나 Runnable 인터페이스를 구현하여 생성.
- 스레드를 실행하려면 start() 메서드를 호출하고, run() 메서드에 정의된 작업이 수행.
class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 실행 중");
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 실행 중");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 스레드 시작
Thread runnableThread = new Thread(new MyRunnable());
runnableThread.start(); // Runnable을 사용한 스레드 시작
}
}스레드 풀 ExecutorService
- 스레드 풀을 사용하면 여러 스레드를 효율적으로 관리.
Executors.newFixedThreadPool(n)을 통해 고정 크기의 스레드 풀을 만들 수 있음.- 작업은
submit()메서드를 통해 제출하며, Future 객체를 통해 결과를 받을 수 있음.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
pool.submit(() -> {
System.out.println(Thread.currentThread().getName() + " 작업 실행");
});
}
pool.shutdown(); // 스레드 풀 종료
}
}
Callable 인터페이스
- Callable 인터페이스는 Runnable과 달리 결과를 반환할 수 있는 작업을 정의할 때 사용.
call()메서드는 작업의 결과를 반환하며, 예외 처리는 ExecutionException을 통해 처리.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableExample {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
Callable<Integer> task = () -> {
return 123;
};
Future<Integer> future = pool.submit(task);
try {
Integer result = future.get(); // 결과 대기
System.out.println("결과: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
pool.shutdown(); // 스레드 풀 종료
}
}
}
데몬 스레드
setDaemon(true)메서드를 사용하여 스레드를 데몬 스레드로 설정.- 데몬 스레드는 JVM이 종료될 때 함께 종료되며, 일반 스레드와 달리 백그라운드에서 실행.
class DaemonThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("데몬 스레드 실행 중...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}
public class DaemonExample {
public static void main(String[] args) {
DaemonThread daemonThread = new DaemonThread();
daemonThread.setDaemon(true); // 데몬 스레드로 설정
daemonThread.start();
// 메인 스레드 대기
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("메인 스레드 종료");
}
}
동기화와 공유 자원
- 스레드 간의 데이터 공유 시, 동기화(synchronization)가 필요.
synchronized키워드를 사용하여 임계 구역을 설정하고 데이터의 일관성을 유지.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SynchronizationExample {
public static void main(String[] args) {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("최종 카운트: " + counter.getCount());
}
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels