프로그래밍언어/Java
자바 쓰레드
개발자명백
2023. 7. 26. 17:16
1. 자바 쓰레드 생성하는 방법
- Thread 클래스 상속
- Runnable 인터페이스 구현
2. 구현하기
Thread 객체를 상속받아 병렬처리 구현하기
import java.util.ArrayList;
class MyThread1 extends Thread {
public MyThread1(String threadName) {
super(threadName);
}
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(this.getName() + " : " + i);
}
System.out.println();
}
}
public class ThreadTest1 {
public static void main(String[] args) throws InterruptedException {
System.out.println("main thread start.");
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 1; i < 3; i++) {
Thread t = new MyThread1("Thread" + i);
t.start(); // 쓰레드 실행
threads.add(t);
}
for (int i = 1; i < 3; i++) {
threads.get(i).join(); // 병합지점
}
System.out.println("main thread end.");
}
}
Runnable 인터페이스를 구현해 병렬처리하기
import java.util.ArrayList;
class MyThread2 implements Runnable {
String threadName;
public MyThread2(String threadName) {
this.threadName = threadName;
}
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(this.threadName + " : " + i);
}
}
}
public class ThreadTest2 {
public static void main(String[] args) throws InterruptedException {
System.out.println("main thread start.");
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 1; i < 3; i++) {
Thread t = new Thread(new MyThread2("Thread" + i));
t.start();
t.join();
threads.add(t);
}
System.out.println("main thread end.");
}
}
3. 특징
- 쓰레드는 순서와 상관없이 동시에 실행된다.
- join 메서드는 병합 지점으로서 쓰레드가 모두 처리될 때까지 메인 쓰레드를 대기한다.
- 병합 지점의 위치에 따라 처리 순서를 다르게 할 수 있다.
- Runnable vs Thread : 보통 쓰레드를 구현할 때 Runnable 인터페이스를 구현한다. Thread를 상속받으면 다른 클래스를 상속받지 못해 제약이 생기며 또한 Runnable 인터페이스는 run 메소드 구현을 강제한다. (추상 메소드)