ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ThreadPriority, Daemon Thread-22.03.30
    고급자바 2022. 3. 30. 14:00
    728x90
    public class T08_ThreadPriorityTest {
    
    	public static void main(String[] args) {
    		System.out.println("최대 우선 순위: "+Thread.MAX_PRIORITY);
    		System.out.println("최소 우선 순위: "+Thread.MIN_PRIORITY);
    		System.out.println("보통 우선 순위: "+Thread.NORM_PRIORITY);
    		
    		Thread[] ths=new Thread[] {
    				new ThreadTest1(),
    				new ThreadTest1(),
    				new ThreadTest1(),
    				new ThreadTest1(),
    				new ThreadTest1(),
    				new ThreadTest2()
    		};
    		// 우선 순위는 start()를 호출하기 전에 설정해야 한다.
    		for(int i=0; i<ths.length; i++) {
    			if(i==5) {
    				ths[i].setPriority(10); //인덱스5가 최대우선순위가 됨
    			}else {
    				ths[i].setPriority(1);
    			}
    		}
    		//우선순위 출력
    		for(Thread th: ths) {
    			System.out.println(th.getName()+ "의 우선순위:"+th.getPriority());
    		}
    		
    		for(Thread th: ths) {
    			th.start();
    		}
    	
    	}
    
    }
    //대문자를 출력하는 스레드
    class ThreadTest1 extends Thread{
    	@Override
    	public void run() {
    		for(char ch='A'; ch<='Z'; ch++){  //A찍고 쉬고 B찍고 쉬고
    				System.out.println(ch);
    				
    				//아무것도 하지 않는 반복문(시간 때우기용)
    				for(long i=1; i<=1000000000; i++) {}
    		}
        }
    }
    
    //소문자를 출력하는 스레드
    class ThreadTest2 extends Thread{
    	@Override
    	public void run() {
    		for(char ch='a'; ch<='z'; ch++){  //A찍고 쉬고 B찍고 쉬고
    				System.out.println(ch);
    				
    				//아무것도 하지 않는 반복문(시간 때우기용)
    				for(long i=1; i<=1000000000; i++) {}
    		}
      }
    }

    이런식으로 알파벳이 끝남... (내생각: 소문자가 우선순위10이기 때문에 먼저 끝난거같음)

    우선순위 방식은 우선순위가 높은 스레드가 실행 상태를 더 많이 가지도록 스케줄링하는 것을 말한다. 


    Daemon Thread

    일반스레드가 있을 때 사용가능하며 일반스레드의 작업을 돕는 보조적인 역할을 수행하는 스레드 이다. 일반 스레드가 모두 종료되면 데몬스레드는 자동으로 종료된다.

    <일반스레드로 했을 때>

    작업내용을 저장한다는것을 무한 반복한다. =>그래서 데몬스레드를 사용한다.

    <데몬스레드 추가해줬을 때>

    스레드를 데몬스레드로 설정하기

    public class T09_ThreadDaemonTest {
    /**
     * 스레드를 데몬스레드로 설정하기
     */
    	public static void main(String[] args) {
    		Thread th=new AutoSaveThread();
    		// 데몬 스레드로 설정하기(Start() 를 호출하기 전에 설정해야 한다.)
    		th.setDaemon(true); //true로 하면 데몬스레드로 설정하겠다.
    		th.start();
    		
    		try {
    			for(int i=1; i<=20; i++) {
    				System.out.println("작업- "+i);
    				Thread.sleep(1000);  //작업 끝내려면 20초 걸림 
    			}
    		} catch (InterruptedException ex) {
    			ex.printStackTrace();
    		}
    		System.out.println("메인스레드 종료...");
    	}
    
    }

    자동저장 기능을 제공하는 스레드(3초에 한번씩 저장)

    class AutoSaveThread extends Thread{
    	@Override
    	public void run() {
    		while(true) {
    			try {
    				Thread.sleep(3000); //3초에 한번씩 잠들고 깨고 
    				
    			} catch (InterruptedException e) {
    				
    				e.printStackTrace();
    			}
    			save(); //저장기능 호출
    		}
    	}
    	
    	public void save() {
    		System.out.println("작업 내용을 저장합니다...");
    	}
    }

    =>th.start();를 하면 AutoSaveThread 의 쓰레드가 실행되고 그리고 메인에 있는 스레드가 실행되어  try문을 실행한다.

    결과적으로는 두개의 스레드가 움직이고 있다고 생각하면 된다.

    728x90

    '고급자바' 카테고리의 다른 글

    Thread yield,Stop,interrupt()-22.03.30  (0) 2022.03.30
    Thread상태-22.03.30  (0) 2022.03.30
    단일, 멀티 Thread-22.03.30  (0) 2022.03.30
    Thread 처리 시간-22.03.30  (0) 2022.03.30
    ThreadTest-22.03.29  (0) 2022.03.29
Designed by Tistory.