Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

Super Coding Addict

Ch15. 자바 Thread 프로그래밍 (3) 본문

JAVA 문법

Ch15. 자바 Thread 프로그래밍 (3)

밍응애 2021. 2. 14. 18:08

* interrupt() 메서드

- interrupt exception 발생시킴

- join(), sleep(), wait() 메서드로 블럭킹된 Thread를 Exception상태에 빠지게 해 다시 runnable상태로 만들 수 있음

 

- 예제

#InterruptTest 클래스

package ch15.thread;

public class InterruptTest extends Thread {
	
	public void run() {
		
		int i;
		for(i=0; i<100; i++) {
			System.out.println(i);
		}
		
		try {
			sleep(5000);
		} catch (InterruptedException e) {
			System.out.println(e);
			System.out.println("Wake!!!");
		}
	}
	
	public static void main(String[] args) {
		InterruptTest test = new InterruptTest();
		test.start();
		test.interrupt();
		
		System.out.println("end");
	}

}

--> interrupt() 메서드를 호출하지 않으면, sleep(5000)으로 5초 후에 Thread가 종료되지만,

     interrupt() 메서드를 호출하면 sleep(5000)으로 블락킹 되었던 Thread가 Exception에 떨어지게 된다

 

* Thread 종료하기

- 서비스에서 Thread가 돌면 무한반복으로 돌리기 때문에 (while(true)) 이 때 Thread를 멈추는 방법?

--> stop() 메서드 사용X

--> while문 안에 flag를 써서, flag의 T / F 따라 돌게끔 함

 

- 예제

# TerminateThread 클래스

package ch15.thread;

import java.io.IOException;

public class TerminateThread extends Thread {

	private boolean flag = false;
	int i;

	public TerminateThread(String name) {
		super(name);
	}

	public void run() {
		while (!flag) {
			try {
				sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(getName() + "end");
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public static void main(String[] args) throws IOException {
		TerminateThread threadA = new TerminateThread("A");
		TerminateThread threadB = new TerminateThread("B");

		threadA.start();
		threadB.start();

		int in;
		while (true) {
			in = System.in.read();
			if (in == 'A') {
				threadA.setFlag(true);
			} else if (in == 'B') {
				threadB.setFlag(true);
			} else if (in == 'M') {
				threadA.setFlag(true);
				threadB.setFlag(true);
				break;
			}
			/*
			 * else { System.out.println("try again"); \n \r
			 */
		}
			System.out.println("main end");
		}
	}

--> flag가 true이면 !flag는 false로 while문을 빠져나오므로 Thread 종료