쓰레드 IO블락킹
import java.util.Scanner;
class ThreadIOTest1 extends Thread {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
try {
System.out.println("Thread = " + i);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class ThreadIOTest2 implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
try {
System.out.println("Runnable = " + i);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class ExThreadIO {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i <= 10; i++) {
try {
System.out.println(i);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("값입력 : ");
String in = sc.next();
System.out.println("입력값은 " + in);
ThreadIOTest1 test1 = new ThreadIOTest1();
ThreadIOTest2 rb = new ThreadIOTest2();
Thread test2 = new Thread(rb);
test1.start();
test2.start();
test2.setPriority(9); //우선순위 설정
System.out.println("값입력 : ");
String in2 = sc.next();
System.out.println("입력값은 " + in2);
sc.close();
}
}
처음 for 문은 for 문이 다 돌고 나서야 입력값을 받을 수 있다.
하지만 멀티쓰레드를 사용하면 for문이 돌때 입력값을 받을 수 있다.
데몬쓰레드
데몬쓰레드는 다른 일반 쓰레드의 작업을 돕는 보조적인 역할을 하는 쓰레드이다.
일반 쓰레드가 종료되면 데몬쓰레드는 강제 종료된다.
데몬쓰레드의 예로 gc, 자동저장 등이 있다.
void setDaemon(true);
setDaemon으로 데몬쓰레드를 설정할 수 있다.
class ThreadDaemonTest implements Runnable {
@Override
public void run() {
while(true) {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("자동저장");
}
}
}
public class ExThreadDaemon {
public static void main(String[] args) {
Thread renew = new Thread(new ThreadDaemonTest());
renew.setDaemon(true);
renew.start();
for (int i = 0; i <= 15; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(i);
System.out.println(renew.getName());
System.out.println(Thread.currentThread());
}
System.out.println("종료");
}
}
자동저장을 데몬쓰레드도 실행했다.
따라서 메인이 끝나면 자동저장도 끝나게 된다.
만약 자동저장을 데몬쓰레드로 설정하지 않는다면 계속 실행된다.
'프로그래밍 > JAVA' 카테고리의 다른 글
쓰레드 실행제어 (0) | 2021.09.26 |
---|---|
쓰레드 상태 및 과정 (0) | 2021.09.24 |
프로세스와 쓰레드(이해와 구현) (0) | 2021.09.19 |
JAVA char <-> String 변환 (0) | 2021.08.25 |
HashMap (0) | 2021.08.19 |