개발일지/Java
Java 스레드 이름 조회 및 설정
E-room
2022. 9. 24. 23:22
728x90
메인 스레드는 main이라는 이름을 가지며, 그 외에 추가적으로 생성한 스레드는 "Thread-n"이라는 이름을 갖는다
스레드 이름 조회하기
.getName()
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Get Thread Name");
}
});
thread.start();
System.out.println("thread.getName() = " + thread.getName());
}
}
// 출력
Get Thread Name
thread.getName()=Thread-0
스레드 이름 설정하기
.setName()
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Set And Get Thread Name");
}
});
thread.start();
System.out.println("thread.getName() = " + thread.getName());
thread.setName("E-room");
System.out.println("thread.getName() = " + thread.getName());
}
}
// 출력
Set And Get Thread Name
thread.getName() = Thread-0
thread.getName() = E-room
스레드 인스턴스의 주소 값 얻기
currentThread() : 실행 중인 스레드의 주소 값을 사용해야 하는 상황에 사용
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
thread.start();
System.out.println(Thread.currentThread().getName());
}
}
//출력
main
Thread-0
728x90