1 분 소요

TIMED_WAITING 스레드 상태

1.동일한 코드를 실행할 경우에 현재 코드를 실행하는 스레드를 식별하기 위한 속성

thread실행을 일시중지 시키는 메소드 -sleep

  • sleep() 호출과 Thread 상태의 변화

new로 스레드 생성하면 계속 기다린다(RUNNABLE) RUNNING-> 특정 메소드 호출(sleep)

공간에 가있다( 잠깐 머무르게 하겠다) : TIME_WAITING TIME OUT이 되면 다시 RUNNABLE로 간다

시간을 다쓰게 되면 양보한다

작업이 끝나면 TERMINATED가 된다

package javastudy;

public class Proagram4 {

	public static void main(String[] args) {

		Runnable subMain = new Runnable() {

			@Override
			public void run() {
				print();
			}
		};

		Thread th1 = new Thread(subMain);
		th1.setName("sub1");
		// 스레드 이름 , 스레드 상태
		System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
		System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
		System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
		System.out.printf("%s: %s\n ", th1.getName(), th1.getState());

		th1.start(); // 꼭 있어야 한다

		Thread th = Thread.currentThread();
		th.setName("Main");

		print();

		System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
		System.out.println("=========Main Exit============");
	}

	private static void print() {

		Thread th = Thread.currentThread();

		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);
		}
	}
}

 sub1: NEW
 sub1: NEW
 sub1: NEW
 sub1: NEW
 sub1[14] : 1
<Main[1] : 1
sub1[14] : 2
<Main[1] : 2
<Main[1] : 3
sub1[14] : 3
<Main[1] : 4
sub1[14] : 4
<Main[1] : 5
sub1[14] : 5
<Main[1] : 6
sub1[14] : 6
<Main[1] : 7
sub1[14] : 7
<Main[1] : 8
sub1[14] : 8
<Main[1] : 9
sub1[14] : 9
. 
.
.
.
sub1: TERMINATED
 =========Main Exit============

카테고리:

업데이트:

댓글남기기