Thread Control 예제

2023. 7. 19. 17:07JAVA

타이어 조립작업을 하는 스레드를 만들고

 

기능메소드를 이용해 아래와 같은 순서로 진행해보자 

 

1. 작업시작  2. 일시정지  3. 다시 시작  4. 작업종료

 

아래를 보면 while문을 사용해 isRun이 true일 경우 작업을 계속하고

 

isWait이 true라면 잠시 멈추는 코드를 작성했다

 

기본적으로 isRun은 true  isWait은 false상태로 시작된다

//특정 작업을 수행하는 직원[스레드] 클래스
class CThread extends Thread{
	
	private boolean isRun= true;
	private boolean isWait= false;
	
	@Override
	public void run() {
		
		while(isRun) {
			//작업 Task 단위
			System.out.println("1번 타이어 조립");
			System.out.println("2번 타이어 조립");
			System.out.println("3번 타이어 조립");
			System.out.println("4번 타이어 조립");
			System.out.println();
			
			if(isWait) {
				//필수로 동기화 처리를 해야 함 
				synchronized (this) {
					try {
						wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			
			//반복문이 너무 빨리 처리되어서..1초간 잠시 정지
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}//while..	
		
		System.out.println("\n퇴근!!\n");
		
	}//run method..

 

 

 

 

2.일시정지 기능

public void pauseThread() {
		this.isWait=true;
	}

3. 다시 시작을 위한 기능

public void resumeThread() {
		
		this.isWait=false;
		
		//반드시 동기화 처리를 같이 해야 함
		synchronized (this) {
			this.notify();//wait된 스레드를 깨움
	}	
}

4.멈춤 기능

public void stopThread() {
		this.isRun = false;
	}

각 기능을 실험해 보는 코드

public class ThreadControlTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 타이어조립 직원객체 생성
		CThread t= new CThread();   
		t.start();
		//t.start(); //error - 스레드는 딱 1번만 start()가 가능함
		
		// 3초 후에 휴식.. 즉, 스레드의 일시정지
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//t.wait();//직접 wait()을 권장하지 않음.
		t.pauseThread();
		
		// 3초 후에 휴식 끝. 작업개시 .. 즉, 스레드 이어하기
		//wait()으로 일시정지된 스레드를 깨워야 함.
		//t.notify(); //직접 notify()를 권장하지 않음
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		t.resumeThread();
		
		// 3초 후에 퇴근..즉, 스레드 종료
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		t.stopThread();

	}//main method..

}//class....

'JAVA' 카테고리의 다른 글

FileOutput(파일 출력)  (0) 2023.07.20
FileInput(파일 입력)  (0) 2023.07.20
Synchronized기능과 예제  (0) 2023.07.19
Runnable  (0) 2023.07.19
Thread(스레드)  (0) 2023.07.19