throws
뒤에는 떠넘겨야 할 예외를 쉼표(,
)로 구분해서 기술한다.throws Exception
으로 작성할 수 있다.📌 새로운 예외를 발생시키기 위해 사용된다 👉 throw에 대한 설명!
throw
로 발생된 예외는 일반적으로 생성자나 메소드 선언부에 throws
로 떠넘겨진다.throw
키워드 뒤에는 예외 객체 생성 코드가 온다.📌 예외를 호출한 곳으로 떠넘기기 위해 메소드 선언부에 작성된다. 👉 throws에 대한 설명!
👉 실행 중인 스레드 상태를 변경하는 것
👉 주어진 시간 동안 일시 정지
InterruptedException
이 발생하므로 예외 처리 필수public class BeepPrintExample1 {
public static void main(String[] args) {
Thread thread = new BeepThread();
thread.start();
for(int i=0; i<5; i++) {
System.out.println("띵");
try { Thread.sleep(500); } catch(InterruptedException e) {}
}
}
}
👉 다른 스레드에게 실행 양보
👉 다른 스레드의 종료를 기다림
👉 스레드 간 협업
👉 스레드가 실행 중인데 즉시 종료할 경우, stop() 메소드 대신 안전하게 스레드를 종료하는 방법
public class PrintThread1 extends Thread {
boolean stop;
public void setStop(boolean stop) {
this.stop = stop;
}
@Override
public void run() {
while(stop==false) {
System.out.println("실행 중");
}
System.out.println("자원 정리");
System.out.println("실행 종료");
}
}
public class StopFlagExample {
public static void main(String[] args) {
PrintThread1 printThread = new PrintThread1();
printThread.start();
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
printThread.setStop(true);
//printThread.stop(); // 갑자기 실행중단됨. stop은 사용하지 않길 권고함
}
}
InterruptedException
을 발생시키는 것을 이용하여 실행 중인 스레드를 종료한다.InterruptedException
이 발생하지 않고, 나중에 일시 정지 상태가 되면 발생한다.public class PrintThread2 extends Thread {
@Override
public void run() {
// 아래의 try나 while문 중 하나를 사용할 수 있다.
// try {
// while(true) {
// System.out.println("실행 중");
// Thread.sleep(1); // 스레드를 일부러 일시 정지시켜 예외 발생 유도
// }
// } catch(InterruptedException e) {
// System.out.println(e.getMessage()); // interrupt는 예외를 발생시켜서 강제로 빠져나가게 하므로 catch에 interrupt 발생 시 할 작업을 넣어준다.
// } finally {
// System.out.println("마무리 작업");
// }
while(true) {
System.out.println("실행 중");
if(Thread.interrupted()) { // 현재 스레드가 interrupted되었는지 확인용
System.out.println("마무리 작업");
break;
}
}
System.out.println("마무리 작업");
}
}
public class InterruptExample {
public static void main(String[] args) {
Thread thread = new PrintThread2();
thread.start();
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
thread.interrupt();
}
}
👉 주 스레드의 작업을 돕는 보조적인 역할을 수행하는 스레드
주 스레드가 종료되면 데몬 스레드도 강제 자동 종료
데몬 스레드 만드는 방법
주 스레드가 데몬 스레드의
setDaemon(true)
를 호출
start()
메소드 호출 전에 데몬 스레드를 호출해야 IllegalThreadStateException
이 발생하지 않는다!현재 실행 중인 스레드가 데몬 스레드인지 구별하는 방법
isDaemon()
메소드 사용
public class AutoSaveThread extends Thread {
public void save() {
System.out.println("작업 내용을 저장함.");
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
break;
}
save();
}
}
}
public class DaemonExample {
public static void main(String[] args) {
AutoSaveThread autoSaveThread = new AutoSaveThread();
autoSaveThread.setDaemon(true);
autoSaveThread.start();
try {
Thread.sleep(3000);
} catch(InterruptedException e) {}
System.out.println("메인 스레드 종료");
}
}
현재 스레드가 속한 스레드 그룹의 이름을 얻는 코드
ThreadGroup group = Thread.currentThread.getThreadGroup();
String groupName = group.getName();
스레드 그룹을 명시적으로 생성하는 코드
ThreadGroup tg = new ThreadGroup(String name);
ThreadGroup tg = new ThreadGroup(ThreadGroup parent, String name);