728x90
프로세스) 운영체제에서의 실행 중인 하나의 애플리케이션
스레드) 여러가지 작업을 동시에 수행할 수 있게 하는 것
스레드 생성하는 방법
- Thread 클래스를 상속받는 방법
- Runnable 인터페이스를 구현하는 방법
1) Thread 클래스를 상속받는 방법
public class MyThread1 extends Thread {
String str;
public MyThread1(String str){
this.str = str;
}
@Override
public void run() {
// 생성자에서 받은 문자열을 10번 출력
for(int i=0; i<10; i++){
System.out.print(str);
try {
//컴퓨터가 너무 빠르기 때문에 수행결과를 잘 확인할 수 없어서
// Thread.sleep() 메서드를 이용해서 조금씩 쉬었다가 출력할 수 있게 함
// sleep 메소드는 익셉션이 발생
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExam1 {
public static void main(String[] args) {
// 생성자로 String값인 str(문자열)을 받기로 함
MyThread1 t1 = new MyThread1("*");
MyThread1 t2 = new MyThread1("-");
// 스레드 동작시 앞에서 오버로딩한 run()을 호출하는 것이 아니라
// start()를 호출함
t1.start();
t2.start();
System.out.print("!!!!!");
}
}
메인 스레드가 종료했음에도 불구하고 프로그램이 종료된는 것은 아니다.
다른 모든 스레드들이 흐름이 종료되어야 프로그램이 종료된다.
2) Runnable 인터페이스를 구현하는 방법
public class MyThread2 implements Runnable {
String str;
public MyThread2(String str){
this.str = str;
}
public void run(){
for(int i = 0; i < 10; i ++){
System.out.print(str);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadExam2 {
public static void main(String[] args) {
MyThread2 r1 = new MyThread2("*");
MyThread2 r2 = new MyThread2("-");
// MyThread2는 Thread를 상속받지 않았기 때문에 Thread가 아님
// Thread를 생성하고 해당 생성자에 MyThread2를 넣어서 Thread를 생성함
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
System.out.print("!!!!!");
}
}
자바는 단일 상속만 지원하기 때문에 이미 어떤 클래스를 상속받고 있다면 Thread를 상속받을 수 없다.
따라서 Thread를 상속하는 것보다 Runnable 인터페이스를 구현하는 것이 다형성면에서도 좋은 방법이다.
728x90
'강의 정리하기 > JAVA' 카테고리의 다른 글
Thread와 상태 제어 (0) | 2023.03.11 |
---|---|
Thread와 공유 객체 (0) | 2023.03.10 |
어노테이션 (0) | 2023.03.10 |
자바 IO(2) (1) | 2023.03.10 |
자바 IO(1) (0) | 2023.03.10 |