본문 바로가기

자바기초

Thread

Process

실행중인 프로그램

OS로부터 메모리를 할당 받음.

 

Thread

실제 프로그램이 수행되는 작업의 최소 단위

하나의 프로세스는 하나 이상의 Thread를 가지게 됨.

 

Multi-thread 프로그래밍

동시에 여러 개의 Thread가 수행되는 프로그래밍

Thread는 각각의 작업공간(context)를 가짐.

공유 자원이 있는 경우 race condition이 발생.

critical section에 대한 동기화(synchronization)의 구현이 필요.

 

더보기

Runnable ---------- sleep(시간), wait(), join() ----------> Not Runnable

- sleep(시간) : 시간 지나면

- wait() : notify()

- join() : other thread exits

 

Thread 우선순위

Thread.MIN_PRIORITY(=1) ~ Thread.MAX_PRIORITY(=10)

디폴트 우선 순위 : Thread.NORM_PRIORITY(=5)

 

setPriority(int newPriority)

int getPriority()

우선 순위가 높은 thread는 CPU를 배분 받을 확률이 높음(차이는 미미하기에 확실히 차별을 주려면 큰 값을 주도록)

 

 

join() 메서드

다른 thread의 결과를 보고 진행해야 하는 일이 있는 경우 join() 메서드를 활용

join() 메서드를 호출한 thread가 non-runnable 상태가 됨.

package thread;

public class JoinTest extends Thread{
	int start;
	int end;
	int total;
	
	public JoinTest(int start, int end) {
		this.start = start;
		this.end = end;
	}
	public void run() {
		int i;
		for(i=start; i<=end; i++) {
			total+=i;
		}
	}
	public static void main(String[] args) {
		JoinTest jt1 = new JoinTest(1, 50);
		JoinTest jt2 = new JoinTest(51, 100);
		
		jt1.start();
		jt2.start();
		
		try {
			jt1.join();
			jt2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int total = jt1.total + jt2.total;
		
		System.out.println("jt1.total = " + jt1.total);
		System.out.println("jt2.total = " + jt2.total);
		System.out.println(total);
	}
}

 

 

interrupt() 메서드

다른 thread에 예외를 발생시키는 interrupt를 보냄

thread가 join(), sleep(), wait() 메서드에 의해 블로킹되었다면 interrupt에 의해 다시 runnable 상태가 될 수 있음.

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

}

 

 

Thread 종료하기

데몬등 무한 반복하는 thread가 종료될 수 있도록 run() 메서드 내의 while문을 활용.

Thread.stop()은 사용하지 않음.

package 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) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(getName()+" end");
	}

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

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

		t1.start();
		t2.start();

		int in;
		while (true) {
			in = System.in.read();
			if (in == 'A') {
				t1.setFlag(true);
			} else if (in == 'B') {
				t2.setFlag(true);
			} else if (in == 'M') {
				t1.setFlag(true);
				t2.setFlag(true);
				break;
			} else {
				System.out.println("try again");
			}
		}
		System.out.println("main end");
	}
}

 

'자바기초' 카테고리의 다른 글

디버깅  (0) 2020.11.27
JDBC / MySQL Driver  (0) 2020.06.15
인터페이스  (0) 2020.06.08
추상 클래스 응용 - 템플릿 메서드  (0) 2020.05.30
추상 클래스  (0) 2020.05.30