상세 컨텐츠

본문 제목

JAVA Thread (Daemon, join() )

BackEnd/JAVA

by H_Develop 2022. 8. 3. 12:37

본문

Thread - CPU의 작업 프로세스 처리(Time Slot) 을 이용한 작업 분할.
 - single Thread ( 객체를 만든 다음, obj.run )
 - multi Thread( obj.start()하면 내부적으로 obj.run() ), 
 - Runnable Interface를 사용한 Thread 생성, 재사용성과 여러 클래스 상속(interface)이 가능, 프로그램 일관성 유지
 - Daemon Thread : 다른 일반 쓰레드의 작업을 돕는, 보조하는 역할한다.

                                함께 구동중인 일반 쓰레드가 종료되면, 데몬 쓰레드도 같이 종료된다.
                                예를 들어, 문서를 작성하는 도중에 3초 간격으로 자동 세이브가 필요한 경우,
                                이런 데몬 쓰레드를 이용할 수 있다.
 - 쓰레드의 Join 기능 : 하나의 쓰레드가 끝난 뒤, 이어서 (새로운|기존 계속) 작업하는 것이 Join이다

 

 

 

 

Daemon Thread

 

public class one implements Runnable {	// ~ extends Thread {} 로 사용하는데, 이건 인터페이스기에 implements를 사용
	static boolean autoSave = false;	// 불리언 변수 생성과 초기값 설정
	
	public static void main(String[] args) {
		one dm = new one();
		Thread th = new Thread(dm);		// Runnable은 start()함수를 쓰기위해선 이렇게 만들어 주어야 한다.
		th.setDaemon(true);				// 추상 메서드
		th.start();						// 추상 메서드, 내부적으로 run() 자동 실행

		for(int i=1; i<=15; i++) {
			try {
			Thread.sleep(1000);
			}	catch (Exception e) {}
			System.out.println();
			if(i==3) { 					// 3초 뒤에 자동 세이브.
				autoSave = true;
			}
			System.out.println("프로그램 종료");
		}
	}

	public void run() {
		while(true) {
			try {
				Thread.sleep(3000);
			} catch (Exception e) {}
			if(autoSave==true) {
				System.out.println("자동 저장됩니다.");
			}
		}
	}
}

 

 

 

Thread join()

 

public class df implements Runnable {

	@Override
	public void run() {	
				System.out.println("run");
				first();
	}
	public void first(){
		System.out.println("first");
		second();
	}
	public void second(){
		System.out.println("second");
	}
	public static void main(String[] args) {
		System.out.println("Starting main class");
		df tt1 = new df();
		Thread tt2 = new Thread(tt1);
		tt2.start();
        // try {
		// 	Thread.sleep(1);
		// } catch (Exception e) {
		// 	e.printStackTrace();
		// }
		System.out.println("Ending main class");
	}	
}

Starting main class
Ending main class
run
first
second
이렇게 ending main class 가 먼저 출력

 

 

public class one implements Runnable {
	public static void main(String[] args) {
		System.out.println("메인 클래스 시작");
		one tj = new one();
		Thread th1 = new Thread(tj);
//		Runnable th2 = new one();
		th1.start();		// 추상 메서드
		
		try {
			th1.join();		// 추상 메서드, 위에 프린트함수 출력 후, th1.start() 완료될 때까지 밑에 프린트 함수는 대기.
		} catch (Exception e) {
//			printStack;
		}
		System.out.println("메인 클래스 종료");
		Thread th2 = new Thread(tj);
		th2.start();
		System.out.println("메인 클래스 종료2");
	}
	
	public void run() {
		System.out.println("run()");
		first();	// 함수 호출
		
	}
	public void first() {
		System.out.println("first()");
		second();
	}
	public void second() {
		System.out.println("second()");
	}
	
}

메인 클래스 시작
run()
first()
second()
메인 클래스 종료
메인 클래스 종료2
run()
first()
second()

순차적으로 출력

 

 

 

 

import java.util.Scanner;
public class df implements Runnable  {
	private int n;
//	public void ThCount (int n) {
//		this.n = n;
//	}
	public df (int n) {
		this.n = n;
	}
	public static void main(String[] args) {
		System.out.println("정수를 입력해 주세요");
		Scanner scan = new Scanner(System.in);
//		df tc = new df();
//		tc.n = scan.nextInt();
//		Thread th = new Thread(tc);
//		th.start();

		df tc = new df(scan.nextInt());
		Thread th = new Thread(tc);
		th.start();
	}
	public void run() {
		for (int i=n; i>=0; i--) {
			try {
			System.out.println(i);
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
		System.out.println("Ending");
	}
	
}

정수를 입력해 주세요
3
3
2
1
0
Ending

 

df method와 객체를 주석하고 현 주석처리된 것들을 열어주어도 같이 사용된다.

관련글 더보기