Thread 식별 속성

창진·2023년 7월 11일
0

자바 백엔드

목록 보기
4/5

각 스레드는 고유한 속성을 가지고 있습니다. 현재 실행 중인 스레드를 구별하기 위해 이를 통해 여러 스레드 중에서 특정 스레드를 식별할 수 있습니다.

스레드가 가지고 있는 속성

thread.getId() = 시스템에 의해 부여된 id 사용
thread.gatName() = 직접 부여하는(기본값 있음)

코드

package thread;

public class name {

	public static void main(String[] args) {
		
		 Runnable subMain = new Runnable() {
				@Override
				public void run() {
					print();
				}
			};
		
		
		Thread th1 = new Thread(subMain);
		th1.setName("sub1");
		Thread th2 = new Thread(subMain);
		th2.setName("sub2");
       
		
        th1.start();
		th2.start();
		
		Thread th = Thread.currentThread(); 
		th.setName("Main");
		print();

	}
	
	public static void print() {
		
		Thread th = Thread.currentThread(); // 현재의 thread의 정보를 얻기위한 메소드
		
		
		for(int i=0; i<100; i++) {
			
			try {
				Thread.sleep(20);  // 성능이 높아서 늦추고자 사용합니다.
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if( th.getName().equals("Main")){
				System.out.printf("<%s[%d]:%d>\n", th.getName(), th.getId(), i+1);
			}
			else {
				System.out.printf("%s[%d]:%d\n", th.getName(), th.getId(), i+1);
			}
			
			
		}
		
	}
	

}

결과

스레드의 ID와 사용자가 부여한 이름이 출력되어 확인할 수 있어, 각각의 스레드를 쉽게 구분할 수 있습니다.

profile
안녕하세요

0개의 댓글

관련 채용 정보