main 스레드
main 메서드의 코드를 수행하는 스레드
스레드는 '사용자 스레드'와 '데몬 스레드(보조 스레드)' 두 종류가 있음
실행 중인 사용자 스레드가 하나도 없을 때 프로그램은 종료됨
싱글 스레드와 멀티 스레드
싱글 스레드
class ThreadTest {
public static void main(String args[]) {
for(int i=0; i < 300; i++)
System.out.printf("%s", new String("-"));
}
for(int i=0; i < 300; i++)
System.out.printf("%s", new String("|"));
}
}
}
멀티 스레드
class ThreadTest {
public static void main(String args[]) {
MyThread1 th1 = new MyThread1();
MyThread2 th2 = new MyThread2();
th1.start();
th2.start();
}
}
class MyThread1 extends Thread {
public void run() {
for(int i=0; i<300; i++) {
System.out.println("-");
}
}
}
class MyThread2 extends Thread {
public void run() {
for(int i=0; i<300; i++) {
System.out.println("|");
}
}
}
멀티 스레드에서 A->B, B->A로 바뀌는 것을 문맥 교환이라고 한다. 이 과정 때문에 싱글 스레드보다 멀티 스레드의 작업시간이 더 걸릴 수 있다.
스레드의 I/O 블로킹(blocking)
입출력 시 작업이 중단되는 것을 I/O 블로킹이라고 한다.
import javax.swing.JOptionPane;
class ThreadEx06 {
public static void main(String[] args) throws Exception
{
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
System.out.println("입력하신 값은 " + input + "입니다.");
for(int i=10; i > 0; i--) {
System.out.println(i);
try {
Thread.sleep(1000); // 1초간 시간을 지연한다.
} catch(Exception e ) {}
}
}
}
사용자의 입력을 기다리는 동안 프로그램은 정지 상태가 된다.
import javax.swing.JOptionPane;
class ThreadEx07 {
public static void main(String[] args) throws Exception {
ThreadEx7_1 th1 = new ThreadEx7_1();
th1.start();
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
System.out.println("입력하신 값은 " + input + "입니다.");
}
}
class ThreadEx7_1 extends Thread {
public void run() {
for(int i=10; i > 0; i--) {
System.out.println(i);
try {
sleep(1000);
} catch(Exception e ) {}
}
}
}
사용자의 입력을 기다리는 동안 다른 작업이 가능하다.
이처럼 두 스레드가 서로 다른 자원을 사용하는 작업의 경우에는 싱글 스레드 프로세스보다 멀티 스레드 프로세스가 더 효율적이다.
'JAVA' 카테고리의 다른 글
[Thread] sleep(), interrupt()와 interrupted() (0) | 2023.02.26 |
---|---|
[Thread] 데몬 스레드, 스레드의 상태 (0) | 2023.02.26 |
[Thread] 스레드의 우선순위 (0) | 2023.02.26 |
[Thread] 프로세스와 스레드, 스레드의 구현과 실행 (0) | 2023.02.26 |
[Collections Framework] Comparator, Comparable (0) | 2023.02.24 |