JAVA

Thread status ( 쓰레드 상태 ) -활용

Stater 2019. 10. 27. 09:00

쓰레드 상태표시

 

Thread 우선순위

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

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

 

사용해서 설정도 가능하다.

-setPriority(int newPriority)

-int getPriority()

 

우선순위가 높은 thread는 CPU를 배분 받을 확률이 높음

 

join() 메서드

 

 

예제코드

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();
		
		//join()걸면 정상적으로 값이 출력 
		//join()이 걸지 않으면 정상적으로 값이 출력X
		try {
			jt1.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			jt2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int total = jt1.total +jt2.total;
		
		System.out.println(jt1.total);
		System.out.println(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문을 활용

-> while문 활용은 false/true를 사용해서 활용

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

 

Thread예제 코드

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()+"THE 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");
			}
		}
		System.out.println("main End");

	}

}

 

반응형